package avicit.im.lantop.docmanager.deptdocarrange.action.service.impl;

import avicit.cbb.billdefine.service.BillDefineManagerIntfsService;
import avicit.cbb.businessclass.fondsmanage.action.DBConnectionCustomManager;
import avicit.cbb.tabledefine.service.CommTableManagerIntfsService;
import avicit.cbb.techclass.elefileconvert.service.impl.JProperties;
import avicit.cbb.techclass.tabledefine.commtablemanager.domain.CbbTables;
import avicit.im.lantop.archiveclassmanager.service.ArchiveClassManagerIntfsService;
import avicit.im.lantop.common.StringUtil;
import avicit.im.lantop.docmanager.deptdocarrange.action.service.DeptdocarrangeService;
import avicit.im.lantop.docmanager.deptdocarrange.service.DeptdocarrangeService;
import avicit.im.lantop.docmanager.deptdocmanager.dao.DeptdocmanagerDao;
import avicit.im.lantop.docmanager.mydocmanager.domain.LantopFileShare;
import avicit.im.lantop.docmanager.mydocmanager.domain.LantopSubmit;
import avicit.im.lantop.docmanager.mydocmanager.domain.LantopSubmitItem;
import avicit.platform6.bpm.web.service.BpmOperateService;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.JsonUtils;
import avicit.platform6.commons.utils.PojoUtil;
import avicit.platform6.commons.utils.web.TreeNode;
import avicit.platform6.core.domain.BeanBase;
import avicit.platform6.core.domain.BeanProcess;
import avicit.platform6.core.exception.DaoException;
import avicit.platform6.core.jdbc.JdbcAvicit;
import avicit.platform6.core.properties.PlatformConstant.OpResult;
import avicit.platform6.core.properties.PlatformConstant.OpType;
import avicit.platform6.core.service.ServiceBase;
import avicit.platform6.generic.constant.CommonFunction;
import avicit.platform6.generic.sqls.SqlAllClass;
import avicit.platform6.modules.system.syslog.service.LogBaseFactory;
import avicit.platform6.modules.system.syslog.service.SysLogUtil;
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;

/**
 * <p>金航数码科技有限责任公司</p>
 * <p>作者：钟一华</p>
 * <p>邮箱：feifan1985@163.com</p>
 * <p>创建时间： 2014-10-27 上午10:22:35 </p>
 * <p>类说明：部门文件管理业务逻辑实现类</p>
 * <p>修改记录： </p>
 */
@Service
@SuppressWarnings("unchecked")
public class DeptdocarrangeServiceImpl extends ServiceBase implements DeptdocarrangeService {

    @Resource
    private ArchiveClassManagerIntfsService archiveClassManagerIntfsService;

    @Autowired
    private BpmOperateService bpmOperateService;

    @Autowired(required = true)
    BillDefineManagerIntfsService billDefineManagerIntfsService;

    @Autowired(required = true)
    private CommTableManagerIntfsService commTableManagerIntfsService;

    @Resource
    private JdbcAvicit jdbcAvicit;

    @Autowired(required = true)
    private DeptdocmanagerDao deptdocmanagerDao;

    @Resource
    JdbcTemplate jdbcTemplate;

    // 获取存储方式
    public static final String SAVE_TYPE = JProperties.getFileProperties("savetype");

    @Override
    public void delete(BeanBase arg0) throws DaoException {
        // TODO Auto-generated method stub

    }

    @Override
    public void insert(BeanBase arg0) throws DaoException {
        // TODO Auto-generated method stub

    }

    @Override
    public void update(BeanBase arg0) throws DaoException {
        // TODO Auto-generated method stub

    }

    /**
     * 获得文件分类数据结构
     */
    @Override
    public List<TreeNode> getDeptDocManagerTreeNodes(String orgId, String deptId, String userId, String ip) throws Exception {
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        // 初始化树先调用存储过程
        List<String> parameter = new ArrayList<String>();
        parameter.add(orgId);
        parameter.add(deptId);
        parameter.add(userId);
        parameter.add(ip);
        this.hibernateDao.callProcedure("LANTOP_DEPT_FILE_TREE_INIT", parameter);
        List<Map<String, Object>> allDeptlist = this.getAllPathListByNodeId(deptId);
        if (allDeptlist.size() < 1) {
            return nodes;
        }
        // 所有节点路径集合
        List<String> allNodePathList = new ArrayList<String>();
        // 部门节点路径集合
        List<String> deptNodePathList = new ArrayList<String>();
        // 获得登陆用户所在部门的节点路径
        for (int i = 0; i < allDeptlist.size(); i++) {
            Map<String, Object> map = allDeptlist.get(i);
            allNodePathList.add(map.get("ARCHIVE_CLASS_NODE_PATH").toString());
            deptNodePathList.add(map.get("ARCHIVE_CLASS_NODE_PATH").toString());
        }
        // 获得共享文件中的路径集合
        List<Map<String, Object>> allFileShareList = this.getFileSharePathByUserIdDeptId(userId, deptId);
        for (int i = 0; i < allFileShareList.size(); i++) {
            Map<String, Object> map = allFileShareList.get(i);
            allNodePathList.add(map.get("ARCHIVE_CLASS_NODE_PATH").toString());
        }
        List<String> newList = new ArrayList<String>(new LinkedHashSet<String>(allNodePathList));
        // 共享节点id集合
        List<String> shareIds = new ArrayList<String>();
        // 将共享数据路径截取获得共享节点id并添加到共享节点id集合中
        for (int i = 0; i < allFileShareList.size(); i++) {
            Map<String, Object> map = allFileShareList.get(i);
            String path = (String) map.get("ARCHIVE_CLASS_NODE_PATH");
            String[] paths = path.split("/");
            if (paths.length >= 3) {
                String id = paths[paths.length - 2];
                shareIds.add(id);
            }
        }
        String sql = this.getSearchSqlByPathList(newList, deptNodePathList);
        nodes = this.getBmwjTreeNodeBySqlAndPid("ROOT", sql, shareIds);
        return nodes;
    }

    /**
     * 通过用户id和部门id获得共享文件中的路径
     *
     * @param userId
     * @param deptId
     * @return
     * @throws Exception List<Map<String,Object>>
     * @throws
     * @author 钟一华
     */
    public List<Map<String, Object>> getFileSharePathByUserIdDeptId(String userId, String deptId) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT DISTINCT LFS.ARCHIVE_CLASS_NODE_PATH\n");
        sbSql.append("FROM LANTOP_FILE_SHARE LFS\n");
        sbSql.append("WHERE LFS.SHARE_USER_ID = ?\n");
        sbSql.append("OR LFS.SHARE_DEPT_ID = ?");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString(), new Object[]{userId, deptId});
        return list;
    }

    /**
     * 拼接树节点查询语句
     */
    public String getSearchSqlByPathList(List<String> allList, List<String> deptList) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("WITH A AS (\n");
        sbSql.append("SELECT T.* FROM LANTOP_ARCHIVE_CLASS T \n");
        if (allList.size() > 0) {
            sbSql.append("WHERE \n");
        }
        for (int i = 0; i < allList.size(); i++) {
            sbSql.append("INSTR('" + allList.get(i) + "', T.ARCHIVE_CLASS_NODE_PATH) > 0\n");
            if (i != allList.size() - 1) {
                sbSql.append(" OR ");
            }
        }
        if (deptList.size() > 0) {
            sbSql.append("UNION ALL\n");
            sbSql.append("SELECT T.* FROM LANTOP_ARCHIVE_CLASS T \n");
            sbSql.append("WHERE \n");
            for (int i = 0; i < deptList.size(); i++) {
                sbSql.append("(INSTR(T.ARCHIVE_CLASS_NODE_PATH, '" + deptList.get(i) + "') > 0\n");
                sbSql.append("AND T.ARCHIVE_CLASS_NODE_PATH != '" + deptList.get(i) + "')\n");
                if (i != deptList.size() - 1) {
                    sbSql.append(" OR ");
                }
            }
        }
        sbSql.append(") SELECT (SELECT COUNT(*) FROM A LAC2\n");
        sbSql.append("  WHERE LAC2.PARENT_ID = LAC1.ID AND ARCHIVE_CLASS_NODE_CODE <> 'LANTOP_PUB_FIELD')\n");
        sbSql.append("  CHILD_COUNT, LAC1.* FROM A LAC1\n");
        sbSql.append("  WHERE  LAC1.PARENT_ID = ? ORDER BY LAC1.NODE_SORT_NUMBER ASC, LAC1.CREATION_DATE ASC");
        return sbSql.toString();
    }

    /**
     * 通过节点id获得路径集合
     *
     * @param id
     * @return
     * @throws Exception List<Map<String,Object>>
     * @throws
     * @author 钟一华
     */
    public List<Map<String, Object>> getAllPathListByNodeId(String id) throws Exception {
        String sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS WHERE ID LIKE '" + id + "_%'";
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
        return list;
    }

    /**
     * 获得部门文件管理树结构
     *
     * @param pid
     * @param sql
     * @return
     * @throws Exception List<TreeNode>
     * @throws
     * @author 钟一华
     */
    public List<TreeNode> getBmwjTreeNodeBySqlAndPid(String pid, String sql, List<String> shareIds) throws Exception {
        List<TreeNode> nodeList = new ArrayList<TreeNode>();
        List<Map<String, Object>> archiveClassList = this.jdbcAvicit.getJdbcTemplate().queryForList(sql, pid);
        // 将业务数据格式转换成esayui树形格式，此处封装了一个TreeNodeVo节点
        for (Map<String, Object> row : archiveClassList) {
            String rid = (String) row.get("id");
            String rname = (String) row.get("archive_class_node_name");
            // 将共享数据的节点更改为 个人共享/部门共享
            for (int i = 0; i < shareIds.size(); i++) {
                if (rid.equals(shareIds.get(i))) {
                    rname = "「共享」" + rname;
                    break;
                }
            }
            TreeNode node = new TreeNode();
            node.setId(rid);
            node.setText(rname);
            String archiveType = (String) row.get("ARCHIVE_TYPE");
            String nodeType = (String) row.get("ARCHIVE_CLASS_NODE_TYPE");
            String parentId = (String) row.get("PARENT_ID");
            node.setId(rid);
            node.setText(rname);
            // 根据节点类型,设置节点图标
            if (null != parentId && "ROOT".equals(parentId)) { // 根节点
                node.setIconCls("icon-im-newnorg");
            } else if (null != archiveType && "-1".equals(archiveType) && null == nodeType) { // 档案类型 -1 物理表
                node.setIconCls("icon-im-newntable");
            } else if (null != archiveType && "0".equals(archiveType) && null == nodeType) { // 0 模版文件夹
                node.setIconCls("icon-im-newnmodulefile");
            } else if (null != archiveType && "1".equals(archiveType) && null == nodeType) { // 1 标识文件
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "2".equals(archiveType) && null == nodeType) { // 2 档案
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "3".equals(archiveType) && null == nodeType) { // 3 专题库
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "4".equals(archiveType) && null == nodeType) { // 4 多媒体
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "5".equals(archiveType) && null == nodeType) { // 5 项目归档计划
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "6".equals(archiveType) && null == nodeType) { // 6 管务
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "7".equals(archiveType) && null == nodeType) { // 7 其他
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != archiveType && "10".equals(archiveType) && null == nodeType) { // 10 虚拟表
                node.setIconCls("icon-im-newnmodulelib");
            } else if (null != nodeType && "1".equals(nodeType)) { // 节点类型 1 文件夹
                node.setIconCls("icon-im-newnmodulefile");
            } else if (null != nodeType && "2".equals(nodeType)) { // 数据节点
                node.setIconCls("icon-im-newndatanode");
            }
            node.setAttributes(row);
            BigDecimal childCount2 = BigDecimal.valueOf(Long.valueOf(row.get("CHILD_COUNT") + ""));
            if (null != childCount2 && childCount2.longValue() > 0) {
                List<TreeNode> cnodes = this.getBmwjTreeNodeBySqlAndPid(rid, sql, shareIds);
                node.getChildren().addAll(cnodes);
                node.setState("open");
            } else {
                node.setState("open");
            }
            nodeList.add(node);
        }
        return nodeList;
    }

    /**
     * 获得所有文件分类数据结构
     */
    @Override
    public List<TreeNode> getAllDeptDocManagerTreeNodes(String orgId, String deptId, String userId, String ip, List<String> deptIdList) throws Exception {
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        // 初始化树先调用存储过程
        List<String> parameter = new ArrayList<String>();
        parameter.add(orgId);
        parameter.add(deptId);
        parameter.add(userId);
        parameter.add(ip);
        this.hibernateDao.callProcedure("LANTOP_DEPT_FILE_TREE_INIT", parameter);
        List<String> allDeptList = new ArrayList<String>();
        for (int i = 0; i < deptIdList.size(); i++) {
            List<Map<String, Object>> deptList = this.getAllPathListByNodeId(deptIdList.get(i));
            for (int j = 0; j < deptList.size(); j++) {
                Map<String, Object> map = deptList.get(j);
                allDeptList.add((String) map.get("ARCHIVE_CLASS_NODE_PATH"));
            }
        }
        String sql = this.getSearchSqlByPathListByDept(allDeptList);
        nodes = this.getBmwjTreeNodeBySqlAndPid("ROOT", sql, new ArrayList<String>());
        return nodes;
    }

    /**
     * 通过部门id路径获得树结构查询sql
     *
     * @param deptList
     * @return
     * @throws Exception String
     * @throws
     */
    public String getSearchSqlByPathListByDept(List<String> deptList) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("WITH A AS (\n");
        sbSql.append("SELECT T.* FROM LANTOP_ARCHIVE_CLASS T \n");
        if (deptList.size() > 0) {
            sbSql.append("WHERE \n");
            for (int i = 0; i < deptList.size(); i++) {
                sbSql.append("INSTR('" + deptList.get(i) + "', T.ARCHIVE_CLASS_NODE_PATH) > 0\n");
                if (i != deptList.size() - 1) {
                    sbSql.append(" OR ");
                }
            }
            sbSql.append("UNION ALL\n");
            sbSql.append("SELECT T.* FROM LANTOP_ARCHIVE_CLASS T \n");
            sbSql.append("WHERE \n");
            for (int i = 0; i < deptList.size(); i++) {
                sbSql.append("(INSTR(T.ARCHIVE_CLASS_NODE_PATH, '" + deptList.get(i) + "') > 0\n");
                sbSql.append("AND T.ARCHIVE_CLASS_NODE_PATH != '" + deptList.get(i) + "')\n");
                if (i != deptList.size() - 1) {
                    sbSql.append(" OR ");
                }
            }
        }
        sbSql.append(") SELECT (SELECT COUNT(*) FROM A LAC2\n");
        sbSql.append("  WHERE LAC2.PARENT_ID = LAC1.ID AND ARCHIVE_CLASS_NODE_CODE <> 'LANTOP_PUB_FIELD')\n");
        sbSql.append("  CHILD_COUNT, LAC1.* FROM A LAC1\n");
        sbSql.append("  WHERE  LAC1.PARENT_ID = ? ORDER BY LAC1.NODE_SORT_NUMBER ASC, LAC1.CREATION_DATE ASC");
        return sbSql.toString();
    }

    /**
     * 归档信息保存方法
     */
    @Override
    public BeanProcess saveSubmitData(LantopSubmit ls, Map<String, Object> parameter) throws Exception {
        String id = ComUtil.getId();
        ls.setId(id);
        PojoUtil.setSysProperties(ls, OpType.insert);
        this.hibernateDao.save(ls);
        SysLogUtil.log(ls, null, OpType.insert, OpResult.success);
        if (null == parameter) {
            throw new Exception("启动流程失败,请传递流程启动参数");
        }
        String processDefId = (String) parameter.get("processDefId");
        String formCode = (String) parameter.get("formCode");
        String userId = (String) parameter.get("userId");
        String deptId = (String) parameter.get("deptId");
        String path = (String) parameter.get("path");
        String processInstanceId = null; // 流程实例ID
        String taskUrl = ""; // 待办url
        if (processDefId == null || processDefId.equals("")) {
            throw new Exception("启动流程失败，缺少流程定义ID！");
        }
        Map<String, Object> variables = new HashMap<String, Object>();
        // 把表单对象转换成map,传递给流程变量
        Map<String, Object> pojoMap = (Map<String, Object>) PojoUtil.toMap(ls);
        // 流程待办标题
        String flowUndoTitle = (String) pojoMap.get("submitTitile");
        variables.putAll(pojoMap);
        variables.put("f_todo_title", flowUndoTitle);
        variables.put("path", path);
        processInstanceId = bpmOperateService.startProcessInstanceById(processDefId, formCode, userId, deptId, variables);
        // // 取待办URL，如果不需要直接打开可以注释以下代码//
        taskUrl = bpmOperateService.getTaskUrl(String.valueOf(processInstanceId), userId);
        // 返回对象
        BeanProcess bp = new BeanProcess();
        bp.setFormId(id);
        bp.setProcessInstanceId(processInstanceId);
        bp.setTaskUrl(taskUrl);
        return bp;
    }

    /**
     * 归档信息明细保存方法
     */
    @Override
    public String saveSubmitItemData(LantopSubmitItem lsi) throws Exception {
        String id = ComUtil.getId();
        lsi.setId(id);
        PojoUtil.setSysProperties(lsi, OpType.insert);
        this.hibernateDao.save(lsi);
        SysLogUtil.log(lsi, null, OpType.insert, OpResult.success);
        return id;
    }

    /**
     * 获得共享设置列表集合
     */
    @Override
    public List<Map<String, Object>> getSharelist(String nodeId, String tableId, String sqlIds) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT LFSV.SHARE_DEPTORUSER_ID, LFSV.SHARE_DEPTORUSER_NAME\n");
        sbSql.append("FROM LANTOP_FILE_SHARE_V LFSV\n");
        sbSql.append("WHERE LFSV.ARCHIVE_CLASS_ID = '" + nodeId + "' AND LFSV.ARCHIVE_TABLE_ID = '" + tableId + "'\n");
        sbSql.append("AND LFSV.RECORD_ID IN (" + sqlIds + ")\n");
        sbSql.append("GROUP BY LFSV.SHARE_DEPTORUSER_NAME, LFSV.SHARE_DEPTORUSER_ID");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        return list;
    }

    /**
     * 保存共享设置信息方法
     */
    @Override
    public String saveFileShare(LantopFileShare lfs) throws Exception {
        String id = ComUtil.getId();
        lfs.setId(id);
        PojoUtil.setSysProperties(lfs, OpType.insert);
        this.hibernateDao.save(lfs);
        SysLogUtil.log(lfs, null, OpType.insert, OpResult.success);
        return id;
    }

    /**
     * 删除选中共享设置信息
     */
    @Override
    public void deleteShareData(String id) throws Exception {
        LantopFileShare lfs = this.hibernateDao.get(LantopFileShare.class, id);
        this.hibernateDao.delete(lfs);
        SysLogUtil.log(lfs, null, OpType.delete, OpResult.success);
    }

    /**
     * 通过id获得归档数据
     */

    public String getSubmitByIds(String id) throws Exception {
        String tableName = "";
        String sql = "SELECT TABLE_NAME FROM CBB_TABLES WHERE ID = (SELECT TABLE_ID FROM CBB_TAB_NODE WHERE NODE_ID = '"+id+"')\n";
        List<Map<String, Object>> maps = jdbcAvicit.getJdbcTemplate().queryForList(sql);
        if(maps.size()>0){
           tableName =  maps.get(0).get("TABLE_NAME").toString();
        }
        return tableName;
    }

    /**
     * 通过id获得归档数据
     */
    @Override
    public LantopSubmit getSubmitById(String id) throws Exception {
        LantopSubmit ls = this.hibernateDao.get(LantopSubmit.class,id);
        return ls;
    }

    /**
     * 通过submitid获得submititem数据
     */
    @Override
    public List<LantopSubmitItem> getSubmitItemBySid(String id, String tableId) throws Exception {
        String hql = "from LantopSubmitItem where lantopSubmitId = ? and archiveTableId = ?";
        List<LantopSubmitItem> lsiList = this.hibernateDao.find(hql, new Object[]{id, tableId});
        return lsiList;
    }

    /**
     * 更新归档数据方法
     */
    @Override
    public void updateSubmitData(LantopSubmit ls) throws Exception {
        LantopSubmit oldBean = this.hibernateDao.get(LantopSubmit.class, ls.getId());
        this.hibernateDao.evict(oldBean);
        LantopSubmit newBean = new LantopSubmit();
        PojoUtil.copyProperties(newBean, oldBean, true);
        PojoUtil.copyProperties(newBean, ls, true);
        SysLogUtil.log(newBean, oldBean, OpType.update, OpResult.success);
        PojoUtil.setSysProperties(newBean, OpType.update);
        this.hibernateDao.update(newBean);

    }

    /**
     * 修改流程结束后归档状态
     */
    @Override
    @SuppressWarnings("unused")
    public void updateSubmitStatus(String id, String orgId, String deptId, String userId, String ip) throws Exception {
        try {
            LantopSubmit ls = this.hibernateDao.get(LantopSubmit.class, id);
            String archiveClassId = "";
            String sysId = "";
            String nodeId = "";
            if (null != ls) {
                archiveClassId = ls.getArchiveClassId();
                sysId = ls.getSysId();
                nodeId = ls.getArchiveNodeId();
            }
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("SELECT T.ARCHIVE_TABLE_ID, T.ARCHIVE_TABLE_NAME FROM LANTOP_SUBMIT_ITEM T\n");
            sbSql.append("WHERE T.LANTOP_SUBMIT_ID = ?\n");
            sbSql.append("GROUP BY T.ARCHIVE_TABLE_ID, T.ARCHIVE_TABLE_NAME");
            List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString(), new Object[]{id});
            ls.setRcvUserId(userId);
            ls.setRcvDeptId(deptId);
            ls.setRcvTime(new Date());
            this.updateSubmitData(ls);
            Map<String, Object> updateMap = new HashMap<String, Object>();
            updateMap.put("ARCHIVE_STATUS", "3");
            updateMap.put("ARCHIVE_FLOW_STATUS", "3");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            updateMap.put("ARCHIVE_ACT_DATE", sdf.format(new Date()));
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("modleName", "文件归档");
            for (int i = 0; i < list.size(); i++) {
                String tableFlag = "";
                Map<String, Object> map = list.get(i);
                String tableId = (String) map.get("ARCHIVE_TABLE_ID");
                String tableName = (String) map.get("ARCHIVE_TABLE_NAME");
                // 如果是盒目录归档,则记录盒目录子表tableId,用于归档后附件的归档
                String toFileTableId = "";
                String searchItemSql = "SELECT * FROM LANTOP_SUBMIT_ITEM T WHERE T.LANTOP_SUBMIT_ID = ? AND T.ARCHIVE_TABLE_ID = ?";
                List<Map<String, Object>> searchItemList = this.jdbcAvicit.getJdbcTemplate().queryForList(searchItemSql, new Object[]{id, tableId});
                StringBuffer sb = new StringBuffer();
                for (int j = 0; j < searchItemList.size(); j++) {
                    Map<String, Object> searchMap = searchItemList.get(j);
                    if (j == searchItemList.size() - 1) {
                        sb.append(searchMap.get("ARCHIVE_RCD_ID"));
                    } else {
                        sb.append(searchMap.get("ARCHIVE_RCD_ID") + ";");
                    }
                    tableFlag = tableName.substring(tableName.length() - 3, tableName.length());
                    if ("AJJ".equals(tableFlag)) {
                        List<Map<String, Object>> fileList = this.commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(orgId, deptId, sysId, nodeId, "2");
                        if (fileList.size() > 0) {
                            Map<String, Object> fileMap = fileList.get(0);
                            String fileTableId = (String) fileMap.get("ID");
                            List<Map<String, Object>> fileDataList = this.billDefineManagerIntfsService.getTableFieldsAndDatasBySearchByNoChangeByIntfs(orgId, deptId, sysId, fileTableId, "", "", "AND PARENT_ID = '" + searchMap.get("ARCHIVE_RCD_ID") + "'",
                                    new HashMap<String, Object>());
                            String fileIds = "";
                            for (int k = 0; k < fileDataList.size(); k++) {
                                Map<String, Object> fileDataMap = fileDataList.get(k);
                                if (k == fileDataList.size() - 1) {
                                    fileIds += fileDataMap.get("ID");
                                } else {
                                    fileIds += fileDataMap.get("ID") + ";";
                                }
                            }
                            param.put("ajDataId", searchMap.get("ARCHIVE_RCD_ID"));
                            this.billDefineManagerIntfsService.updateRecordByDataIdsWithUpdateAjByIntfs(orgId, deptId, sysId, nodeId, fileTableId, updateMap, fileIds, param);
                        }
                    } else if ("ATA".equals(tableFlag)) {
                        List<Map<String, Object>> fileList = this.commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(orgId, deptId, sysId, nodeId, "1");
                        if (fileList.size() > 0) {
                            Map<String, Object> fileMap = fileList.get(0);
                            String fileTableId = (String) fileMap.get("ID");
                            toFileTableId = fileTableId;
                            List<Map<String, Object>> fileDataList = this.billDefineManagerIntfsService.getTableFieldsAndDatasBySearchByNoChangeByIntfs(orgId, deptId, sysId, fileTableId, "", "", "AND PARENT_ID = '" + searchMap.get("ARCHIVE_RCD_ID") + "'",
                                    new HashMap<String, Object>());
                            String fileIds = "";
                            for (int k = 0; k < fileDataList.size(); k++) {
                                Map<String, Object> fileDataMap = fileDataList.get(k);
                                if (k == fileDataList.size() - 1) {
                                    fileIds += fileDataMap.get("ID");
                                } else {
                                    fileIds += fileDataMap.get("ID") + ";";
                                }
                            }
                            param.put("ajDataId", searchMap.get("ARCHIVE_RCD_ID"));
                            this.billDefineManagerIntfsService.updateRecordByDataIdsWithUpdateAjByIntfs(orgId, deptId, sysId, nodeId, fileTableId, updateMap, fileIds, param);
                        }
                    }
                }
                param.put("ajDataId", "");
                this.billDefineManagerIntfsService.updateRecordByDataIdsWithUpdateAjByIntfs(orgId, deptId, sysId, nodeId, tableId, updateMap, sb.toString(), param);
                int returnint = -1;
                String returnstring = "";
                String json = "";
                Connection conn = deptdocmanagerDao.getConnection();
                try {
                    CallableStatement ps = null;
                    if ("AJJ".equals(tableFlag)) {
                        ps = conn.prepareCall("call LANTOP_FILE_SUBMIT(?,?,?,?,?,?,?,?,?,?,?,?)");
                    } else if ("ATA".equals(tableFlag)) {
                        ps = conn.prepareCall("call LANTOP_FILE_SUBMIT_BOX(?,?,?,?,?,?,?,?,?,?,?,?)");
                    } else {
                        ps = conn.prepareCall("call LANTOP_FILE_SUBMIT(?,?,?,?,?,?,?,?,?,?,?,?)");
                    }
                    ps.setString(1, orgId);
                    ps.setString(2, deptId);
                    ps.setString(3, sysId);
                    ps.setString(4, nodeId);
                    if ("AJJ".equals(tableFlag)) {
                        ps.setString(5, tableId);
                    } else if ("ATA".equals(tableFlag)) {
                        ps.setString(5, toFileTableId);
                    } else {
                        ps.setString(5, tableId);
                    }
                    ps.setString(6, archiveClassId);
                    ps.setString(7, sb.toString());
                    ps.setString(8, userId);
                    ps.setString(9, ip);
                    // 返回值
                    ps.registerOutParameter(10, Types.VARCHAR);
                    ps.registerOutParameter(11, Types.INTEGER);
                    ps.registerOutParameter(12, Types.VARCHAR);
                    ps.execute();
                    json = (String) ps.getObject(10);
                    returnint = (Integer) ps.getObject(11);
                    returnstring = (String) ps.getObject(12);
                } catch (Exception e) {
                    e.printStackTrace();
                    try {
                        conn.close();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                } finally {
                    conn.close();
                }

                if (null != json && !"".equals(json)) {
                    JSONArray ja = JSONArray.fromObject(json);
                    if (ja.size() == 1) {
                        JSONObject jo = JSONObject.fromObject(ja.get(0));
                        String srcTableId = jo.getString("srcTableId");
                        String tarTableId = jo.getString("tarTableId");
                        for (int j = 0; j < searchItemList.size(); j++) {
                            Map<String, Object> searchMap = searchItemList.get(j);
                            List<Map<String, Object>> tarDataList = this.billDefineManagerIntfsService.getTableFieldsAndDatasBySearchByNoChangeByIntfs(orgId, deptId, sysId, tarTableId, "", "", "AND REF_FILE_ID = '" + searchMap.get("ARCHIVE_RCD_ID") + "'",
                                    new HashMap<String, Object>());
                            if (tarDataList.size() > 0) {
                                Map<String, Object> tarMap = tarDataList.get(0);
                                // this.billDefineManagerIntfsService.insertMongoDbAttachment((String) searchMap.get("ARCHIVE_RCD_ID"), (String) tarMap.get("ID"));
                            }
                        }
                    }
                    if (ja.size() >= 2) {
                        JSONObject jo = JSONObject.fromObject(ja.get(0));
                        // String srcAnTableId = jo.getString("srcTableId");
                        String tarAnTableId = jo.getString("tarTableId");
                        // 循环对归档数据进行附件复制
                        for (int j = 0; j < searchItemList.size(); j++) {
                            Map<String, Object> searchMap = searchItemList.get(j);
                            // 判断是案卷归档还是盒目录归档,如果是案卷级归档,则进行案卷级的附件复制,反之则进行盒目录的附件复制
                            if ("AJJ".equals(tableFlag)) {
                                // 获取归档目标对应数据集合
                                List<Map<String, Object>> tarAnDataList = this.billDefineManagerIntfsService.getTableFieldsAndDatasBySearchByNoChangeByIntfs(orgId, deptId, sysId, tarAnTableId, "", "", "AND REF_FILE_ID = '" + searchMap.get("ARCHIVE_RCD_ID") + "'",
                                        new HashMap<String, Object>());
                                if (tarAnDataList.size() > 0) {
                                    Map<String, Object> tarMap = tarAnDataList.get(0);
                                    // this.billDefineManagerIntfsService.insertMongoDbAttachment((String) searchMap.get("ARCHIVE_RCD_ID"), (String) tarMap.get("ID"));
                                    // 存储数据库
                                }
                                // 复制子级数据
                                jo = JSONObject.fromObject(ja.get(1));
                                String srcFileTableId = jo.getString("srcTableId");
                                String tarFileTableId = jo.getString("tarTableId");
                                if (null != srcFileTableId && !"".equals(srcFileTableId)) {
                                    // 获得源子表对应数据
                                    List<Map<String, Object>> fileDataList = this.billDefineManagerIntfsService.getTableFieldsAndDatasBySearchByNoChangeByIntfs(orgId, deptId, sysId, srcFileTableId, "", "", "AND PARENT_ID = '" + searchMap.get("ARCHIVE_RCD_ID") + "'",
                                            new HashMap<String, Object>());
                                    // 循环复制对应子表数据附件给目标子表数据
                                    for (int l = 0; l < fileDataList.size(); l++) {
                                        Map<String, Object> fileDataMap = fileDataList.get(l);
                                        // 获得对应目标的子表数据
                                        List<Map<String, Object>> tarFileDataList = this.billDefineManagerIntfsService.getTableFieldsAndDatasBySearchByNoChangeByIntfs(orgId, deptId, sysId, tarFileTableId, "", "", "AND REF_FILE_ID = '" + fileDataMap.get("ID") + "'",
                                                new HashMap<String, Object>());
                                        if (tarAnDataList.size() > 0) {
                                            Map<String, Object> tarMap = tarFileDataList.get(0);
                                            // this.billDefineManagerIntfsService.insertMongoDbAttachment((String) fileDataMap.get("ID"), (String) tarMap.get("ID"));
                                            // 存储数据库
                                        }
                                    }
                                }
                            } else {
                                // 获取归档目标对应数据集合
                                List<Map<String, Object>> tarAnDataList = this.billDefineManagerIntfsService.getTableFieldsAndDatasBySearchByNoChangeByIntfs(orgId, deptId, sysId, tableId, "", "", "AND REF_FILE_ID = '" + searchMap.get("ARCHIVE_RCD_ID") + "'",
                                        new HashMap<String, Object>());
                                if (tarAnDataList.size() > 0) {
                                    Map<String, Object> tarMap = tarAnDataList.get(0);
                                    this.billDefineManagerIntfsService.insertMongoDbAttachment((String) searchMap.get("ARCHIVE_RCD_ID"), (String) tarMap.get("ID"));
                                }
                                // 复制子数据
                                // 复制子级数据
                                jo = JSONObject.fromObject(ja.get(1));
                                String srcFileTableId = jo.getString("srcTableId");
                                String tarFileTableId = jo.getString("tarTableId");
                                if (null != srcFileTableId && !"".equals(srcFileTableId)) {
                                    // 获得源子表对应数据
                                    List<Map<String, Object>> fileDataList = this.billDefineManagerIntfsService.getTableFieldsAndDatasBySearchByNoChangeByIntfs(orgId, deptId, sysId, srcFileTableId, "", "", "AND PARENT_ID = '" + searchMap.get("ARCHIVE_RCD_ID") + "'",
                                            new HashMap<String, Object>());
                                    // 循环复制对应子表数据附件给目标子表数据
                                    for (int l = 0; l < fileDataList.size(); l++) {
                                        Map<String, Object> fileDataMap = fileDataList.get(l);
                                        // 获得对应目标的子表数据
                                        List<Map<String, Object>> tarFileDataList = this.billDefineManagerIntfsService.getTableFieldsAndDatasBySearchByNoChangeByIntfs(orgId, deptId, sysId, tarFileTableId, "", "", "AND REF_FILE_ID = '" + fileDataMap.get("ID") + "'",
                                                new HashMap<String, Object>());
                                        if (tarFileDataList.size() > 0) {
                                            Map<String, Object> tarMap = tarFileDataList.get(0);
                                            // this.billDefineManagerIntfsService.insertMongoDbAttachment((String) fileDataMap.get("ID"), (String) tarMap.get("ID"));
                                            // 存储数据库
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 移除归档列表数据方法
     */
    @Override
    public void deleteSubmitItemsById(LantopSubmitItem lsi) throws Exception {
        this.hibernateDao.delete(lsi);
        SysLogUtil.log(lsi, null, OpType.delete, OpResult.success);
    }

    /**
     * 通过submitId和recordId获得item数据
     */
    @Override
    public LantopSubmitItem getSubmitItemById(String recordId, String submitId) throws Exception {
        String hql = "from LantopSubmitItem where archiveRcdId = ? and lantopSubmitId = ?";
        List<LantopSubmitItem> list = this.hibernateDao.find(hql, new Object[]{recordId, submitId});
        LantopSubmitItem lsi = null;
        if (list.size() > 0) {
            lsi = list.get(0);
        }
        return lsi;
    }

    /**
     * 通过数据id获得附件id
     */
    @Override
    public List<String> getAttachIdByRecordId(String recordId) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT ID,ATTACH_NAME,PARENT_TABLE_ID,PARENT_REGISTER_ID,ATTACH_TYPE,ATTACH_SIZE,LAST_UPDATE_DATE,LAST_UPDATED_BY,LAST_UPDATE_IP,CREATION_DATE,CREATED_BY,VERSION,ATTRIBUTE_01,ATTRIBUTE_02,ATTRIBUTE_03,ATTRIBUTE_04,ATTRIBUTE_05,ATTRIBUTE_06,ATTRIBUTE_07,ATTRIBUTE_08,ATTRIBUTE_09,ATTRIBUTE_10,UPLOAD_PATH,PARENT_TABLE_FIELD,ATTACH_CATEGORY,SECRET_LEVEL,FASTDFS_LOCATION FROM SYS_ATTACHMENT WHERE ID IN (SELECT ATTACHMENT_ID FROM CBB_DOC_RELATION WHERE RECORD_ID = ? AND IF_DELETE = 'N')");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString(), new Object[]{recordId});
        List<String> attach = new ArrayList<String>();
        if (list.size() > 0) {
            Map<String, Object> map = list.get(0);
            attach.add(map.get("ID").toString());
            attach.add(map.get("ATTACH_TYPE").toString());
            attach.add(list.size() + "");
        }
        return attach;
    }


    /**
     * 通过数据id获得附件信息
     */
    @Override
    public List<Map<String, Object>> getClassNodeId(String recordId) throws Exception {
        String sql = "SELECT T.ID,T.TABLE_NAME,T.TABLE_TITLE FROM CBB_TABLES T WHERE T.ID IN (SELECT TABLE_ID FROM CBB_TAB_NODE WHERE NODE_ID = '"+recordId+"')";
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
        return list;
    }


    /**
     * 通过数据id获得附件id
     */
    @Override
    public List<Map<String, Object>> getSourceName(String recordId) throws Exception {
        String sql = "SELECT T.ID,T.TABLE_TITLE FROM CBB_TABLES T WHERE T.ID IN (SELECT TABLE_ID FROM CBB_TAB_NODE WHERE NODE_ID = '"+recordId+"')";
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
        return list;
    }

    /**
     * 通过数据id获得附件id
     */
    @Override
    public List<Map<String, Object>> getSourceNames(String recordId) throws Exception {
        String sql = "SELECT T.ID,T.TABLE_TITLE FROM CBB_TABLES T WHERE T.ID  = '"+recordId+"'";
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
        return list;
    }

    /**
     * 通过数据id获得附件id
     */
    @Override
    public Map<String, Object> getOrgId(String recordId) throws Exception {
        String sql = "SELECT T.ID,T.TABLE_NAME,T.TABLE_TITLE FROM CBB_TABLES T WHERE T.ID = (SELECT TABLE_ID FROM CBB_TAB_NODE WHERE NODE_ID = '"+recordId+"')";
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
        Map<String, Object> map = new HashMap<>();
        if (list.size() > 0) {
            map = list.get(0);
        }
        return map;
    }

    /**
     * 获得流程状态
     */
    @Override
    public String checkStatusById(String id) throws Exception {
        String sql = "SELECT * FROM BPM_HIST_PROCINST WHERE FORMID_ = ?";
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql, new Object[]{id});
        String status = "";
        if (list.size() > 0) {
            Map<String, Object> map = list.get(0);
            status = map.get("BUSINESSSTATE_").toString();
        }
        return status;
    }

    /**
     * 通过共享用户和部门id,和数据id获得共享id
     */
    @Override
    public List<Map<String, Object>> getShareListByRecordIdsAndShareIds(String nodeId, String tableId, String shareSqlIds, String recordSqlIds) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT * FROM LANTOP_FILE_SHARE_V\n");
        sbSql.append("WHERE RECORD_ID IN (" + recordSqlIds + ")\n");
        sbSql.append("AND SHARE_DEPTORUSER_ID IN (" + shareSqlIds + ")\n");
        sbSql.append("AND ARCHIVE_CLASS_ID = '" + nodeId + "'\n");
        sbSql.append("AND ARCHIVE_TABLE_ID = '" + tableId + "'");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        return list;
    }

    /**
     * 通过归档id反查获得tableId
     */
    @Override
    public String getTableIdByFormId(String id) throws Exception {
        String tableId = "";
        LantopSubmit ls = this.hibernateDao.get(LantopSubmit.class, id);
        if (null != ls) {
            tableId = ls.getArchiveTableId();
        }
        return tableId;
    }

    /**
     * 获得目标档案库列表
     */
    @Override
    public List<Map<String, Object>> getTargetTreeNode(String tableId) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT T.ID,\n");
        sbSql.append(" T.ORG_ID,\n");
        sbSql.append(" T.DEPT_ID,\n");
        sbSql.append(" T.SYS_ID,\n");
        sbSql.append(" T.SOURCE_TABLE_ID,\n");
        sbSql.append(" T.SOURCE_TABLE_NAME,\n");
        sbSql.append(" T.SOURCE_TABLE_TITLE,\n");
        sbSql.append(" T.TGT_TABLE_ID,\n");
        sbSql.append(" T.TGT_TABLE_NAME,\n");
        sbSql.append(" T.TGT_TABLE_TITLE,\n");
        sbSql.append(" LAC.ARCHIVE_CLASS_NODE_CODE,\n");
        sbSql.append(" LAC.ARCHIVE_CLASS_NODE_NAME,\n");
        sbSql.append(" LAC.ID AS SOURCEID\n");
        sbSql.append("FROM LANTOP_FIELD_RELATE_SET T\n");
        sbSql.append("LEFT JOIN LANTOP_ARCHIVE_CLASS LAC\n");
        sbSql.append("ON LAC.ID = T.TGT_ARCHIVE_CLASS_ID\n");
        sbSql.append("WHERE 1 = 1\n");
        sbSql.append("and tgt_table_name <> 'LANTOP_PUB_FIELD'\n");
        sbSql.append("and source_table_id = '" + tableId + "'");
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        return list;
    }

    /**
     * 判断选中数据是否提交流程
     */
    @Override
    public boolean checkRecordIsFlag(String ids) throws Exception {
        String[] arrayIds = ids.split(";");
        String sqlIds = "";
        for (int i = 0; i < arrayIds.length; i++) {
            sqlIds += "'" + arrayIds[i] + "',";
        }
        if (sqlIds.length() > 0) {
            sqlIds = sqlIds.substring(0, sqlIds.length() - 1);
        }
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT * FROM LANTOP_SUBMIT_ITEM T\n");
        sbSql.append("WHERE T.ARCHIVE_RCD_ID IN (" + sqlIds + ")");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 判断数据是否存在共享
     */
    @Override
    public boolean isExistShareByRecordId(String id) throws Exception {
        String hql = "from LantopFileShare where recordId = ?";
        List<LantopFileShare> lfsList = this.hibernateDao.find(hql, new Object[]{id});
        if (lfsList.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 取消共享设置
     */
    @Override
    public void deleteShareDataByRecord(String id) throws Exception {
        String hql = "from LantopFileShare where recordId = ?";
        List<LantopFileShare> lfsList = this.hibernateDao.find(hql, new Object[]{id});
        for (int i = 0; i < lfsList.size(); i++) {
            LantopFileShare lfs = lfsList.get(i);
            this.hibernateDao.delete(lfs);
            SysLogUtil.log(lfs, null, OpType.delete, OpResult.success);
        }
    }

    /**
     * 判断选中数据是否对本部门进行过共享
     */
    @Override
    public boolean isExistFileShareByDataIdAndDeptId(String dataId, String deptId) throws Exception {

        String hql = "from LantopFileShare where shareDeptId = ? and recordId = ?";
        List<LantopFileShare> lfsList = this.hibernateDao.find(hql, new Object[]{deptId, dataId});
        if (lfsList.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 通过tableid和部门id获得共享数据
     */
    @Override
    public List<LantopFileShare> getShareDataIdsByTableIdAndDeptId(String nodeId, String tableId, String deptId, String userId) throws Exception {
        String sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS T WHERE ID = '" + nodeId + "'";
        List<Map<String, Object>> nodeList = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
        List<LantopFileShare> allList = new ArrayList<LantopFileShare>();
        if (nodeList.size() > 0) {
            sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS T WHERE PARENT_ID = '" + nodeList.get(0).get("PARENT_ID") + "'";
            nodeList = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
            for (int i = 0; i < nodeList.size(); i++) {
                Map<String, Object> map = nodeList.get(i);
                String hql = "from LantopFileShare where archiveClassId = ? and archiveTableId = ? and (shareDeptId = ? or shareUserId = ?)";
                List<LantopFileShare> list = this.hibernateDao.find(hql, new Object[]{map.get("ID"), tableId, deptId, userId});
                allList.addAll(list);
            }
        }
        return allList;
    }

    /**
     * 通过部门信息获得共享信息集合
     *
     * @param parent
     * @param deptId
     * @return
     * @throws Exception
     * @throws
     */
    @Override
    public List<LantopFileShare> getShareDataIdsByParentAndDeptId(String parent, String deptId) throws Exception {
        String hql = "from LantopFileShare where archiveClassId in (" + parent + ") and shareDeptId = ?";
        List<LantopFileShare> list = this.hibernateDao.find(hql, new Object[]{deptId});
        return list;
    }

    /**
     * 获得目标档案库树结构数据
     */
    @Override
    public List<TreeNode> getTargetDatasByTableId(String tableId) throws Exception {
        // 字段对应设置,是否为模版级别
        boolean isFlag = false;
        String ids = "";
        String orgId="";
        // StringBuffer sbSql = new StringBuffer();
        // sbSql.append("SELECT T.TGT_ARCHIVE_CLASS_ID CLASS_ID\n");
        // sbSql.append("  FROM LANTOP_FIELD_RELATE_SET T\n");
        // sbSql.append("  LEFT JOIN LANTOP_ARCHIVE_CLASS LAC\n");
        // sbSql.append("    ON T.TGT_ARCHIVE_CLASS_ID = LAC.ID\n");
        // sbSql.append(" WHERE T.SOURCE_TABLE_ID = '" + tableId + "'");
        // List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        // for (int i = 0; i < list.size(); i++) {
        // Map<String, Object> map = list.get(i);
        // String id = (String)map.get("CLASS_ID");
        // if (null == id || "".equals(id)) {
        // isFlag = true;
        // break;
        // }
        // ids += id + ";";
        // }
        List<TreeNode> datas = this.recurFindTreeNodesByParentId(tableId, "ROOT", isFlag, ids,orgId);
        return datas;
    }


    /**
     * 获得目标档案库树结构数据
     */
    public List<TreeNode> getTargetDatasByTableIdAndOrgId(String tableId, String OrgId) throws Exception {
        // 字段对应设置,是否为模版级别
        boolean isFlag = false;
        String ids = "";
        String id = "";
        if (OrgId != null && !OrgId.equals("")) {
            id = OrgId;
        } else {
            id = "ROOT";
        }
        List<TreeNode> datas = this.recurFindTreeNodesByParentId(tableId, "ROOT", isFlag, ids,OrgId);
        return datas;
    }

    /**
     * 获取树结构信息集合
     *
     * @param tableId
     * @param id
     * @param isFlag
     * @param ids
     * @return
     * @throws Exception List<TreeNode>
     * @throws
     */
    public List<TreeNode> recurFindTreeNodesByParentId(String tableId, String id, boolean isFlag, String ids, String orgId) throws Exception {
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        // 查询业务数据
        List<Map<String, Object>> childTreeList = findNodesByParentId(tableId, id, isFlag, ids,orgId);
        try {
            // 将业务数据格式转换成esayui树形格式，此处封装了一个TreeNodeVo节点
            for (Map<String, Object> row : childTreeList) {
                String rid = (String) row.get("id");
                String rname = (String) row.get("archive_class_node_name");
                TreeNode node = new TreeNode();
                node.setId(rid);
                node.setText(rname);
                // 根据节点类型,设置节点图标
                String archiveType = (String) row.get("ARCHIVE_TYPE");
                String nodeType = (String) row.get("ARCHIVE_CLASS_NODE_TYPE");
                String rootId = (String) row.get("PARENT_ID");
                // 根据节点类型,设置节点图标
                if (null != rootId && "ROOT".equals(rootId)) { // 根节点
                    node.setIconCls("icon-im-newnorg");
                } else if (null != archiveType && "-1".equals(archiveType) && null == nodeType) { // 档案类型 -1 物理表
                    node.setIconCls("icon-im-newntable");
                } else if (null != archiveType && "0".equals(archiveType) && null == nodeType) { // 0 模版文件夹
                    node.setIconCls("icon-im-newnmodulefile");
                } else if (null != archiveType && "1".equals(archiveType) && null == nodeType) { // 1 标识文件
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "2".equals(archiveType) && null == nodeType) { // 2 档案
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "3".equals(archiveType) && null == nodeType) { // 3 专题库
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "4".equals(archiveType) && null == nodeType) { // 4 多媒体
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "5".equals(archiveType) && null == nodeType) { // 5 项目归档计划
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "6".equals(archiveType) && null == nodeType) { // 6 管务
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "7".equals(archiveType) && null == nodeType) { // 7 其他
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "10".equals(archiveType) && null == nodeType) { // 10 虚拟表
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != nodeType && "1".equals(nodeType)) { // 节点类型 1 文件夹
                    node.setIconCls("icon-im-newnmodulefile");
                } else if (null != nodeType && "2".equals(nodeType)) { // 数据节点
                    node.setIconCls("icon-im-newndatanode");
                }
                node.setAttributes(row);
                BigDecimal childCount2 = BigDecimal.valueOf(Long.valueOf(row.get("CHILD_COUNT") + ""));
                if (null != childCount2 && childCount2.longValue() > 0) {
                    List<TreeNode> cnodes = recurFindTreeNodesByParentId(tableId, rid, isFlag, ids,orgId);
                    node.getChildren().addAll(cnodes);
                    node.setState("open");
                } else {
                    node.setState("open");
                }
                nodes.add(node);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nodes;
    }

    /**
     * 通过父id获取树节点信息集合
     *
     * @param tableId
     * @param parentId
     * @param isFlag
     * @param ids
     * @return
     * @throws Exception List<Map<String,Object>>
     * @throws
     */
    public List<Map<String, Object>> findNodesByParentId(String tableId, String parentId, boolean isFlag, String ids,String orgId) throws Exception {
        Assert.notNull(parentId, "参数不能为空！");
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("WITH T1 AS\n");
        sbSql.append(" (SELECT DISTINCT T.TGT_TABLE_ID,NVL(T.TGT_ARCHIVE_CLASS_ID,'1') AS TGT_ARCHIVE_CLASS_ID\n");
        sbSql.append("    FROM LANTOP_FIELD_RELATE_SET T\n");
        sbSql.append("    LEFT JOIN LANTOP_ARCHIVE_CLASS LAC\n");
        sbSql.append("      ON LAC.ID = T.TGT_ARCHIVE_CLASS_ID\n");
        sbSql.append("   WHERE 1 = 1\n");
        sbSql.append("     AND T.TGT_TABLE_NAME <> 'LANTOP_PUB_FIELD'\n");
        sbSql.append("     AND T.SOURCE_TABLE_ID = ?\n");
        sbSql.append("     ),\n");
        sbSql.append("T2 AS\n");
        sbSql.append(" (SELECT CTN.NODE_ID\n");
        sbSql.append("    FROM CBB_TAB_NODE CTN\n");
        sbSql.append("    INNER JOIN LANTOP_ARCHIVE_CLASS LAC\n");
        sbSql.append("      ON LAC.ID = CTN.NODE_ID\n");
        sbSql.append("   INNER JOIN T1\n");
        sbSql.append("   ON CTN.TABLE_ID = T1.TGT_TABLE_ID\n");
        sbSql.append("   WHERE T1.TGT_ARCHIVE_CLASS_ID = '1'\n");
        sbSql.append("   UNION ALL\n");
        sbSql.append("   SELECT T1.TGT_ARCHIVE_CLASS_ID FROM T1 WHERE T1.TGT_ARCHIVE_CLASS_ID <> '1'),\n");
        sbSql.append("T3 AS\n");
        sbSql.append(" (SELECT LAC1.*, SYS_CONNECT_BY_PATH(LAC1.ID, '/') PH\n");
        sbSql.append("    FROM LANTOP_ARCHIVE_CLASS LAC1\n");
        sbSql.append("   WHERE ARCHIVE_CLASS_NODE_CODE NOT IN ('BMWJ', 'GRWJ')\n");
        sbSql.append("  CONNECT BY PRIOR LAC1.ID = LAC1.PARENT_ID\n");
        sbSql.append("   START WITH LAC1.PARENT_ID = 'ROOT'\n");
        sbSql.append("   ORDER BY LAC1.CREATION_DATE ASC, LAC1.NODE_SORT_NUMBER ASC),\n");
        sbSql.append("T4 AS\n");
        sbSql.append(" (SELECT * FROM T3 WHERE T3.ID IN (SELECT * FROM T2)),\n");
        sbSql.append("T5 AS\n");
        sbSql.append(" (SELECT T3.*\n");
        sbSql.append("    FROM T4, T3\n");
        sbSql.append("   WHERE INSTR(T3.PH, T4.ID) > 0\n");
        sbSql.append("  UNION\n");
        sbSql.append("  SELECT T3.* FROM T4, T3 WHERE INSTR(T4.PH, T3.PH) > 0)\n");
        sbSql.append("SELECT (SELECT COUNT(*) FROM T5 T51 WHERE T51.PARENT_ID = T5.ID) CHILD_COUNT, T5.*\n");
        sbSql.append("  FROM T5\n");
        sbSql.append("  WHERE PARENT_ID = ? \n");
        sbSql.append("AND org_id='"+orgId+"'");
        sbSql.append("CONNECT BY PRIOR T5.ID = T5.PARENT_ID\n");
        sbSql.append(" START WITH T5.PARENT_ID = 'ROOT'");
        sbSql.append(" ORDER BY T5.NODE_SORT_NUMBER ASC");
        if (sbSql.length() > 0) {
            list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString(), new Object[]{tableId, parentId});
        }
        return list;
    }

    /**
     * 通过parentId获得叶子节点id
     */
    @Override
    public List<Map<String, Object>> getChildNodeIdByParentId(String parentId) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT ID FROM LANTOP_ARCHIVE_CLASS LAC\n");
        sbSql.append("CONNECT BY PRIOR LAC.ID = LAC.PARENT_ID\n");
        sbSql.append("START WITH ID = '" + parentId + "'");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        return list;
    }

    /**
     * 根据节点ID获得父节点ID
     */
    @Override
    public String getParentNodeIdById(String nodeId) throws Exception {
        String sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS WHERE ID = '" + nodeId + "'";
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
        String pId = "";
        if (list.size() > 0) {
            Map<String, Object> map = list.get(0);
            pId = (String) map.get("PARENT_ID");
        }
        return pId;
    }

    /**
     * 通过数据id获得共享数据集合
     */
    @Override
    public List<LantopFileShare> getShareListByRecordId(String recordId) throws Exception {
        String hql = "from LantopFileShare where recordId = ?";
        List<LantopFileShare> list = this.hibernateDao.find(hql, new Object[]{recordId});
        return list;
    }

    /**
     * 通过nodeid获得选择节点树结构
     */
    @Override
    public List<Map<String, Object>> getSelectNodesByStartNodeId(String startNodeId) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT * FROM LANTOP_ARCHIVE_CLASS T\n");
        sbSql.append("CONNECT BY PRIOR T.ID = T.PARENT_ID\n");
        sbSql.append("START WITH PARENT_ID = ?");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString(), new Object[]{startNodeId});
        return list;
    }

    /**
     * 树查询方法
     */
    @Override
    public List<TreeNode> getSearchTreeBySearchData(String loginUserId, String loginUserDeptId, String value) throws Exception {

        List<Map<String, Object>> allDeptlist = this.getAllPathListByNodeId(loginUserDeptId);
        // 所有节点路径集合
        List<String> allNodePathList = new ArrayList<String>();
        // 部门节点路径集合
        List<String> deptNodePathList = new ArrayList<String>();
        // 获得登陆用户所在部门的节点路径
        for (int i = 0; i < allDeptlist.size(); i++) {
            Map<String, Object> map = allDeptlist.get(i);
            allNodePathList.add(map.get("ARCHIVE_CLASS_NODE_PATH").toString());
            deptNodePathList.add(map.get("ARCHIVE_CLASS_NODE_PATH").toString());
        }
        // 获得共享文件中的路径集合
        List<Map<String, Object>> allFileShareList = this.getFileSharePathByUserIdDeptId(loginUserId, loginUserDeptId);
        for (int i = 0; i < allFileShareList.size(); i++) {
            Map<String, Object> map = allFileShareList.get(i);
            allNodePathList.add(map.get("ARCHIVE_CLASS_NODE_PATH").toString());
        }
        List<String> newList = new ArrayList<String>(new LinkedHashSet<String>(allNodePathList));
        List<TreeNode> treeNodes = new ArrayList<TreeNode>();
        List<String> pathList = this.getSearchNodePathListBySearchDataAndNodePaths(value, newList, deptNodePathList);
        if (pathList.size() > 0) {
            // 通过nodePath拼接查询树形结构数据
            String sql = this.getSearchSqlByPathList(pathList);
            treeNodes = this.getBmwjTreeNodeBySqlAndPid("ROOT", sql, new ArrayList<String>());
        }
        return treeNodes;
    }

    /**
     * 获取查询树结构集合
     *
     * @param value
     * @param allNodePathList
     * @param deptNodePathList
     * @return
     * @throws Exception List<String>
     * @throws
     */
    public List<String> getSearchNodePathListBySearchDataAndNodePaths(String value, List<String> allNodePathList, List<String> deptNodePathList) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("WITH A AS (\n");
        sbSql.append("SELECT T.* FROM LANTOP_ARCHIVE_CLASS T \n");
        if (allNodePathList.size() > 0) {
            sbSql.append("WHERE \n");
        }
        for (int i = 0; i < allNodePathList.size(); i++) {
            sbSql.append("INSTR('" + allNodePathList.get(i) + "', T.ARCHIVE_CLASS_NODE_PATH) > 0\n");
            if (i != allNodePathList.size() - 1) {
                sbSql.append(" OR ");
            }
        }
        if (deptNodePathList.size() > 0) {
            sbSql.append("UNION ALL\n");
            sbSql.append("SELECT T.* FROM LANTOP_ARCHIVE_CLASS T \n");
            sbSql.append("WHERE \n");
            for (int i = 0; i < deptNodePathList.size(); i++) {
                sbSql.append("(INSTR(T.ARCHIVE_CLASS_NODE_PATH, '" + deptNodePathList.get(i) + "') > 0\n");
                sbSql.append("AND T.ARCHIVE_CLASS_NODE_PATH != '" + deptNodePathList.get(i) + "')\n");
                if (i != deptNodePathList.size() - 1) {
                    sbSql.append(" OR ");
                }
            }
        }
        sbSql.append(") SELECT ARCHIVE_CLASS_NODE_PATH FROM A WHERE UPPER(ARCHIVE_CLASS_NODE_NAME) LIKE UPPER('%" + value + "%')");
        List<String> pathList = new ArrayList<String>();
        List<Map<String, Object>> findList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        for (int i = 0; i < findList.size(); i++) {
            Map<String, Object> map = findList.get(i);
            pathList.add((String) map.get("ARCHIVE_CLASS_NODE_PATH"));
        }
        return pathList;
    }

    /**
     * 拼接树节点查询语句
     */
    public String getSearchSqlByPathList(List<String> pathList) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("WITH A AS (\n");
        sbSql.append("SELECT T.* FROM LANTOP_ARCHIVE_CLASS T \n");
        if (pathList.size() > 0) {
            sbSql.append("WHERE \n");
        }
        for (int i = 0; i < pathList.size(); i++) {
            sbSql.append("INSTR('" + pathList.get(i) + "', T.ARCHIVE_CLASS_NODE_PATH) > 0\n");
            if (i != pathList.size() - 1) {
                sbSql.append(" OR ");
            }
        }
        // if (deptList.size() > 0) {
        // sbSql.append("UNION ALL\n");
        // sbSql.append("SELECT T.* FROM LANTOP_ARCHIVE_CLASS T \n");
        // sbSql.append("WHERE \n");
        // for (int i = 0; i < deptList.size(); i++) {
        // sbSql.append("(INSTR(T.ARCHIVE_CLASS_NODE_PATH, '" + deptList.get(i) + "') > 0\n");
        // sbSql.append("AND T.ARCHIVE_CLASS_NODE_PATH != '" + deptList.get(i) + "')\n");
        // if (i != deptList.size() - 1) {
        // sbSql.append(" OR ");
        // }
        // }
        // }
        sbSql.append(") SELECT (SELECT COUNT(*) FROM A LAC2\n");
        sbSql.append("  WHERE LAC2.PARENT_ID = LAC1.ID)\n");
        sbSql.append("  CHILD_COUNT, LAC1.* FROM A LAC1\n");
        sbSql.append("  WHERE  LAC1.PARENT_ID = ?");
        return sbSql.toString();
    }

    /**
     * 通过节点id和部门id获得向上向下节点数据
     */
    @Override
    public List<Map<String, Object>> getTableDataByNodeId(String nodeId, String deptId) throws Exception {
        String sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS WHERE ID = '" + nodeId + "'";
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
        if (list.size() > 0) {
            Map<String, Object> map = list.get(0);
            String parentId = (String) map.get("PARENT_ID");
            sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS WHERE ID = '" + parentId + "' AND (ARCHIVE_CLASS_NODE_TYPE IS NULL OR ARCHIVE_CLASS_NODE_TYPE = '')";
            list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
            if (list.size() > 0) {
                Map<String, Object> nodeMap = list.get(0);
                sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS WHERE PARENT_ID = '" + nodeMap.get("ID") + "' AND ARCHIVE_CLASS_NODE_CODE = 'BMWJ'";
                list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
                if (list.size() > 0) {
                    nodeMap = list.get(0);
                    sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS WHERE PARENT_ID = '" + nodeMap.get("ID") + "' AND INSTR(ID, '" + deptId + "') > 0";
                    list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
                    return list;
                }
            } else {
                list = this.getTableDataByNodeId(parentId, deptId);
            }
        }
        return list;
    }

    /**
     * 根据节点路径获得树结构数据
     */
    @Override
    public List<TreeNode> getSelectNodesByPath(String path, String parentId) throws Exception {
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        // 查询业务数据
        List<Map<String, Object>> childTreeList = findNodesByPath(path, parentId);
        try {
            // 将业务数据格式转换成esayui树形格式，此处封装了一个TreeNodeVo节点
            for (Map<String, Object> row : childTreeList) {
                String rid = (String) row.get("id");
                String rname = (String) row.get("archive_class_node_name");
                TreeNode node = new TreeNode();
                node.setId(rid);
                node.setText(rname);
                // 根据节点类型,设置节点图标
                String archiveType = (String) row.get("ARCHIVE_TYPE");
                String nodeType = (String) row.get("ARCHIVE_CLASS_NODE_TYPE");
                String rootId = (String) row.get("PARENT_ID");
                // 根据节点类型,设置节点图标
                if (null != rootId && "ROOT".equals(rootId)) { // 根节点
                    node.setIconCls("icon-im-newnorg");
                } else if (null != archiveType && "-1".equals(archiveType) && null == nodeType) { // 档案类型 -1 物理表
                    node.setIconCls("icon-im-newntable");
                } else if (null != archiveType && "0".equals(archiveType) && null == nodeType) { // 0 模版文件夹
                    node.setIconCls("icon-im-newnmodulefile");
                } else if (null != archiveType && "1".equals(archiveType) && null == nodeType) { // 1 标识文件
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "2".equals(archiveType) && null == nodeType) { // 2 档案
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "3".equals(archiveType) && null == nodeType) { // 3 专题库
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "4".equals(archiveType) && null == nodeType) { // 4 多媒体
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "5".equals(archiveType) && null == nodeType) { // 5 项目归档计划
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "6".equals(archiveType) && null == nodeType) { // 6 管务
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "7".equals(archiveType) && null == nodeType) { // 7 其他
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "10".equals(archiveType) && null == nodeType) { // 10 虚拟表
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != nodeType && "1".equals(nodeType)) { // 节点类型 1 文件夹
                    node.setIconCls("icon-im-newnmodulefile");
                } else if (null != nodeType && "2".equals(nodeType)) { // 数据节点
                    node.setIconCls("icon-im-newndatanode");
                }
                node.setAttributes(row);
                BigDecimal childCount2 = BigDecimal.valueOf(Long.valueOf(row.get("CHILD_COUNT") + ""));
                if (null != childCount2 && childCount2.longValue() > 0) {
                    List<TreeNode> cnodes = getSelectNodesByPath(path, rid);
                    node.getChildren().addAll(cnodes);
                    node.setState("open");
                } else {
                    node.setState("open");
                }
                nodes.add(node);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nodes;
    }

    /**
     * 根据路径和父节点id获得数据
     *
     * @param path
     * @param parentId
     * @return
     * @throws Exception List<Map<String,Object>>
     * @throws
     * @author 钟一华
     */
    public List<Map<String, Object>> findNodesByPath(String path, String parentId) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("WITH A AS (\n");
        sbSql.append("     SELECT T.* FROM LANTOP_ARCHIVE_CLASS T\n");
        sbSql.append("     WHERE INSTR('" + path + "', T.ARCHIVE_CLASS_NODE_PATH) > 0\n");
        sbSql.append("     UNION ALL\n");
        sbSql.append("     SELECT * FROM LANTOP_ARCHIVE_CLASS T\n");
        sbSql.append("     WHERE INSTR(T.ARCHIVE_CLASS_NODE_PATH, '" + path + "') > 0\n");
        sbSql.append("     AND T.ARCHIVE_CLASS_NODE_PATH != '" + path + "'");
        sbSql.append(") SELECT (SELECT COUNT(*) FROM A LAC2\n");
        sbSql.append("  WHERE LAC2.PARENT_ID = LAC1.ID)\n");
        sbSql.append("  CHILD_COUNT, LAC1.* FROM A LAC1\n");
        sbSql.append("  WHERE  LAC1.PARENT_ID = ? ORDER BY LAC1.NODE_SORT_NUMBER ASC, LAC1.CREATION_DATE ASC");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString(), parentId);
        return list;
    }

    /**
     * 根据数据ids和部门ids和用户ids查询是否存在共享
     */
    @Override
    public boolean checkFileShareByRecordIdAndShareDeptIdsAndShareUserIds(String[] dataIds, String[] deptIds, String[] userIds) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT * FROM LANTOP_FILE_SHARE WHERE RECORD_ID IN (\n");
        for (int i = 0; i < dataIds.length; i++) {
            sb.append("'" + dataIds[i] + "'");
            if (i != dataIds.length - 1) {
                sb.append(",");
            }
        }
        sb.append(") AND (\n");
        if (deptIds.length > 0) {
            sb.append("SHARE_DEPT_ID IN (");
            for (int i = 0; i < deptIds.length; i++) {
                sb.append("'" + deptIds[i] + "'");
                if (i != deptIds.length - 1) {
                    sb.append(",");
                }
            }
            sb.append(")\n");
        }
        if (userIds.length > 0) {
            if (deptIds.length > 0) {
                sb.append(" OR ");
            }
            sb.append(" SHARE_USER_ID IN (");
            for (int i = 0; i < userIds.length; i++) {
                sb.append("'" + userIds[i] + "'");
                if (i != userIds.length - 1) {
                    sb.append(",");
                }
            }
            sb.append(")\n");
        }
        sb.append(")");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sb.toString());
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 根据数据id获得流程节点值
     */
    @Override
    public String getTaskNumberById(String id) throws Exception {
        String sql = "SELECT V.ACTIVITYNAME_, V.STATE_ FROM BPM_ENTRY_V V WHERE  V.FORMID_ = '" + id + "' ORDER BY V.START_ DESC";
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
        String task = "";
        String status = "";
        if (list.size() > 0) {
            Map<String, Object> map = list.get(0);
            task = (String) map.get("ACTIVITYNAME_");
            status = (String) map.get("STATE_");
        }
        return task + "_" + status;
    }

    /**
     * 通过源表id获得目标节点id
     */
    @Override
    public String getTargetTreeDataBySourceTableId(String sourceTableId) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT DISTINCT(TGT_ARCHIVE_CLASS_ID) FROM LANTOP_FIELD_RELATE_SET\n");
        sbSql.append("WHERE SOURCE_TABLE_ID = '" + sourceTableId + "'\n");
        sbSql.append("AND TGT_ARCHIVE_CLASS_ID IS NOT NULL");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        if (list.size() == 1) {
            Map<String, Object> map = list.get(0);
            return (String) map.get("TGT_ARCHIVE_CLASS_ID");
        } else {
            StringBuffer tgtTableIdSql = new StringBuffer();
            tgtTableIdSql.append("SELECT DISTINCT(TGT_TABLE_ID) FROM LANTOP_FIELD_RELATE_SET\n");
            tgtTableIdSql.append("WHERE SOURCE_TABLE_ID = '" + sourceTableId + "'\n");
            tgtTableIdSql.append("AND TGT_TABLE_NAME != 'LANTOP_PUB_FIELD'");
            List<Map<String, Object>> tgtTableIdList = this.jdbcAvicit.getJdbcTemplate().queryForList(tgtTableIdSql.toString());
            if (tgtTableIdList.size() == 1) {
                Map<String, Object> tgtMap = tgtTableIdList.get(0);
                String sql = "SELECT * FROM LANTOP_ARCHIVE_TAB_CLASS_V WHERE ID = '" + tgtMap.get("TGT_TABLE_ID") + "'";
                List<Map<String, Object>> pList = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
                if (pList.size() > 0) {
                    Map<String, Object> m = pList.get(0);
                    String nodeId = (String) m.get("PARENT_ID");
                    StringBuffer tgtNodeSql = new StringBuffer();
                    tgtNodeSql.append("WITH T1 AS\n");
                    tgtNodeSql.append(" (SELECT T.ARCHIVE_CLASS_NODE_NAME,\n");
                    tgtNodeSql.append("         T.ARCHIVE_CLASS_NODE_CODE,\n");
                    tgtNodeSql.append("         T.ARCHIVE_TYPE,\n");
                    tgtNodeSql.append("         T.ID,\n");
                    tgtNodeSql.append("         SYS_CONNECT_BY_PATH(T.ID, '/') PH,\n");
                    tgtNodeSql.append("         T.PARENT_ID\n");
                    tgtNodeSql.append("    FROM LANTOP_ARCHIVE_CLASS T\n");
                    tgtNodeSql.append("  CONNECT BY PRIOR T.ID = T.PARENT_ID\n");
                    tgtNodeSql.append("   START WITH T.PARENT_ID = 'ROOT'),\n");
                    tgtNodeSql.append("T2 AS\n");
                    tgtNodeSql.append(" (SELECT * FROM T1 WHERE T1.ID = '" + nodeId + "'),\n");
                    tgtNodeSql.append("T3 AS\n");
                    tgtNodeSql.append(" (SELECT T1.*\n");
                    tgtNodeSql.append("    FROM T1, T2\n");
                    tgtNodeSql.append("   WHERE INSTR(T2.PH, T1.ID) > 0\n");
                    tgtNodeSql.append("  UNION\n");
                    tgtNodeSql.append("  SELECT T1.* FROM T1, T2 WHERE INSTR(T1.PH, T2.PH) > 0),\n");
                    tgtNodeSql.append("T4 AS\n");
                    tgtNodeSql.append(" (SELECT LAC.* FROM T3, LANTOP_ARCHIVE_CLASS LAC WHERE LAC.ID = T3.ID)\n");
                    tgtNodeSql.append("SELECT * FROM T4\n");
                    tgtNodeSql.append(" WHERE T4.ARCHIVE_CLASS_NODE_TYPE = '2'");
                    List<Map<String, Object>> tgtNodeList = this.jdbcAvicit.getJdbcTemplate().queryForList(tgtNodeSql.toString());
                    if (tgtNodeList.size() > 0) {
                        Map<String, Object> tgtNodeMap = tgtNodeList.get(0);
                        return (String) tgtNodeMap.get("ID");
                    }
                }
            }
        }
        return "";
    }

    /**
     * 根据名称获取节点ID（用于归档流程最后一步档案库节点选中）
     *
     * @param nodeName
     * @return
     * @throws Exception String
     * @author 郭亮
     */
    @Override
    public String getNodeIdByName(String nodeName) throws Exception {
        String nodeId = "";
        String sql = "SELECT T.ID FROM LANTOP_ARCHIVE_CLASS T WHERE T.ARCHIVE_CLASS_NODE_NAME = '" + nodeName + "'";
        List<String> list = this.hibernateDao.findBySQL(sql);
        if (list.size() > 0) {
            nodeId = list.get(0);
        }
        return nodeId;
    }

    /**
     * 根据归档ID获取归档数据的归档单位名称
     *
     * @param submitId
     * @return
     * @throws Exception
     * @throws
     */
    @Override
    public String getDeptNameBySubmitId(String submitId) throws Exception {
        String deptName = "";
        // 根据submitId查找归档详细信息获取tableID，recordId
        String sql = "SELECT T.ARCHIVE_TABLE_NAME,T.ARCHIVE_RCD_ID FROM LANTOP_SUBMIT_ITEM T WHERE T.LANTOP_SUBMIT_ID = '" + submitId + "'";
        List<Object[]> list = this.hibernateDao.findBySQL(sql);
        if (list.size() > 0) {
            String tabName = (String) list.get(0)[0];
            String rcdId = (String) list.get(0)[1];
            String deptSql = "SELECT T.ARCHIVE_DEPT FROM " + tabName + " T WHERE T.ID = '" + rcdId + "'";
            List<String> deptList = this.hibernateDao.findBySQL(deptSql);
            if (deptList.size() > 0) {
                deptName = deptList.get(0);
            }
        }
        return deptName;
    }

    /**
     * 在归档 流程后处理 之前做唯一索引判断
     */
    @Override
    public Map<String, Object> beforeNotify(String formId, String nodeId) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        Map<String, Object> result = new HashMap<String, Object>();
        String sysId = "";
        String deptId = "";
        String orgId = "";
        String tableName = "";// 归档数据所属 库表 英文名
        String rcdId = "";// 档案记录ID
        String tableId = "";// 归档到档案的库表tableId
        StringBuffer sbSubmit = new StringBuffer();
        sbSubmit.append("SELECT * FROM LANTOP_SUBMIT LS\n");
        sbSubmit.append("WHERE LS.ID = '" + formId + "'");
        // 获取流程归档信息
        List<Map<String, Object>> submitList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSubmit.toString());
        if (submitList.size() > 0) {
            Map<String, Object> map = submitList.get(0);
            sysId = (String) map.get("SYS_ID");
            deptId = (String) map.get("DEPT_ID");
            orgId = (String) map.get("ORG_ID");
            paramMap.put("sysId", sysId);
            paramMap.put("orgId", orgId);
        }
        StringBuffer sbItem = new StringBuffer();
        sbItem.append("SELECT * FROM LANTOP_SUBMIT_ITEM LSI\n");
        sbItem.append("WHERE LSI.LANTOP_SUBMIT_ID = '" + formId + "'");
        // 根据nodeId获取数据节点对应关系信息集合
        List<Map<String, Object>> treeNodeIdList = this.commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(orgId, deptId, sysId, nodeId, "");
        Map<String, Object> modelParam = new HashMap<String, Object>();
        modelParam.put("treeNodeList", treeNodeIdList);
        Map<String, Object> modelMap = this.archiveClassManagerIntfsService.getDataNodeInfoByParam(modelParam);
        int dataCount = Integer.parseInt(modelMap.get("dataCount").toString());
        String fileTableId = "";// 文件tableId
        String archiveTableId = "";// 案卷tableId
        if (dataCount == 1) {// 如果dataCount 是 1 就取 下标是0 的 是 文件级
            fileTableId = (String) treeNodeIdList.get(0).get("ID");
        }
        if (dataCount == 2) {// 如果 dataCount 是 2 取 下标0 就是 案卷 下标1 就是 文件
            fileTableId = (String) treeNodeIdList.get(1).get("ID");
            archiveTableId = (String) treeNodeIdList.get(0).get("ID");
        }
        // 获取归档明细
        List<Map<String, Object>> itemList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbItem.toString());
        if (itemList.size() > 0) {
            for (int i = 0; i < itemList.size(); i++) {
                String tableFlag = "";
                Map<String, Object> map = itemList.get(i);
                tableName = (String) map.get("ARCHIVE_TABLE_NAME");
                rcdId = (String) map.get("ARCHIVE_RCD_ID");
                tableFlag = tableName.substring(tableName.length() - 3, tableName.length());
                if ("AJJ".equals(tableFlag) || "WJJ".equals(tableFlag)) {
                    tableId = archiveTableId;
                } else {
                    tableId = fileTableId;
                }
                paramMap.put("tableId", tableId);
                // 获取归档数据的信息
                StringBuffer sbSql = new StringBuffer();
                sbSql.append("SELECT * FROM " + tableName + " S\n");
                sbSql.append("WHERE S.ID = '" + rcdId + "'");
                List<Map<String, Object>> objList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
                if (objList.size() > 0) {
                    Map<String, Object> mapObj = objList.get(0);
                    paramMap.put("mapObj", mapObj);
                }
                // 获取索引信息
                List<Map<String, Object>> tableIndex = commTableManagerIntfsService.getTableIndexByParam(paramMap);
                boolean isExist = false;// 值是否已存在
                String colLabels = "";// 唯一索引字段
                if (null != tableIndex) {
                    for (Map<String, Object> m : tableIndex) {
                        isExist = ((Boolean) m.get("isExist")).booleanValue();
                        colLabels = (String) m.get("message");
                    }
                }
                result.put("isExist", isExist);
                if (isExist == true) {
                    result.put("message", colLabels);
                    // 将数据还原为未归档前的状态
                    // this.updateStatus(sysId, orgId, deptId, tableName, rcdId);
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 将数据还原成归档前的状态
     * ARCHIVE_STATUS(1.未归档)
     * ARCHIVE_FLOW_STATUS(1.未提交)
     */
    @Override
    public void updateStatus(String sysId, String orgId, String deptId, String tableName, String id) throws Exception {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("UPDATE " + tableName + " T\n");
        sbSql.append("SET T.ARCHIVE_FLOW_STATUS = '1',T.ARCHIVE_STATUS = '1'\n");
        sbSql.append("WHERE T.ID = '" + id + "'");
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("modleName", "文件归档");
        billDefineManagerIntfsService.updateRecordBySqlByIntfs(orgId, deptId, sysId, sbSql.toString(), param);
    }


    /**
     * 迁移
     *
     * @param sysId
     * @param orgId
     * @param deptId
     * @param params ids  数据id字符串
     *               tableId  迁移的表ID
     *               fileType 迁移数据类型，file 文件级；an 案卷级 ； box 盒级
     *               nodeId	节点id
     *               isRetain 是否保留原记录   no 不保留；yes  保留
     *               migrationNodeId  迁移到目标节点Id,
     *               sysId 	系统ID
     *               orgId   组织Id
     *               deptId  部门Id
     *               userId  当前登陆人ID
     *               ip		当前登陆IP
     *               version	//默认版本号未 0
     * @throws Exception String
     * @throws
     */
    @Override
    public String migrationData(String sysId, String orgId, String deptId,
                                Map<String, Object> params, String migrationType) throws Exception {
        //String tableId = (String)params.get("tableId");//迁移表ID
        String fileType = (String) params.get("fileType");//迁移数据类型，file 文件级；an 案卷级 ； box 盒级
        String sourceNodeId = (String) params.get("sourceNodeId");//源节点ID
        String tgtNodeId = (String) params.get("tgtNodeId");//目标节点ID

        //根据源节点ID获得需要迁移数据节点的源表信息
        Map<String, String> sourceTableDatas = getTableDataByNodeId(orgId, deptId, sysId, sourceNodeId);
        String sourceFileTableId = sourceTableDatas.get("fileTableId");//文件级表ID
        String sourceFileTableName = sourceTableDatas.get("fileTableName");//文件级表名称
        String sourceAnTableId = sourceTableDatas.get("anTableId");//案卷或盒级表ID
        String sourceAnTableName = sourceTableDatas.get("anTableName");//案卷或盒级表名称
        //源表信息暂时存储Map中
        params.put("sourceFileTableId", sourceFileTableId);
        params.put("sourceFileTableName", sourceFileTableName);
        params.put("sourceAnTableId", sourceAnTableId);
        params.put("sourceAnTableName", sourceAnTableName);

        //获得目标节点的表信息
        Map<String, String> tgtTableDatas = getTableDataByNodeId(orgId, deptId, sysId, tgtNodeId);
        String tgtFileTableId = tgtTableDatas.get("fileTableId");//文件级表ID
        String tgtFileTableName = tgtTableDatas.get("fileTableName");//文件级表名称
        String tgtAnTableId = tgtTableDatas.get("anTableId");//案卷或盒级表ID
        String tgtAnTableName = tgtTableDatas.get("anTableName");//案卷或盒级表名称
        //目标表信息暂时存储Map中
        params.put("tgtFileTableId", tgtFileTableId);
        params.put("tgtFileTableName", tgtFileTableName);
        params.put("tgtAnTableId", tgtAnTableId);
        params.put("tgtAnTableName", tgtAnTableName);

        params.put("sourceNodeId",sourceNodeId);
        if (fileType.equals("file")) {//文件级
            //判断目标文件级表是否存在
            if (tgtFileTableId.equals("") || tgtFileTableName.equals("")) {
                return "souNot";
            }
            //获得字段对应设置，对应字段
            List<Map<String, Object>> fieldsList = getCorrespondingByTableId1(sourceFileTableId, tgtFileTableId, tgtNodeId, migrationType);
            if(fieldsList.size()==0){
                return "souNot";
            }
            params.put("fileFieldsList", fieldsList);
            //进行文件级迁移工作
            this.fileMigrationData(params);
        } else {//案卷级 和 盒级
            if (tgtAnTableId.equals("") || tgtAnTableName.equals("")) {
                return "souNot";
            }
            if (tgtFileTableId.equals("") || tgtFileTableName.equals("")) {
                return "souNot";
            }

            //获得文件级 字段对应设置，对应字段
            List<Map<String, Object>> fileFieldsList = getCorrespondingByTableId(sourceFileTableId, tgtFileTableId, tgtNodeId);
            //判断文件级是否有字段对应设置
            if (fileFieldsList.size() == 0) {
                return "souNotTgt";
            }
            params.put("fileFieldsList", fileFieldsList);
            //获得案卷级 字段对应设置，对应字段
            List<Map<String, Object>> anFieldsList = getCorrespondingByTableId(sourceAnTableId, tgtAnTableId, tgtNodeId);
            //判断案卷或盒级是否有字段对应设置
            if (anFieldsList.size() == 0) {
                return "souNotTgt";
            }
            params.put("anFieldsList", anFieldsList);

            //进行迁移工作
            anMigrationData(params);
        }
        return "success";
    }

    /**
     * @param nodeId 节点ID
     * @return java.lang.String
     * @Title: getArchiveTypeByNode
     * @Description: 根据节点ID查询档案类型
     * @date 2019-07-27
     * @author HuangJian
     */
    private String getArchiveTypeByNode(String nodeId) {
        String sql = "SELECT * FROM LANTOP_ARCHIVE_CLASS WHERE ID = '" + nodeId + "'";
        Map<String, Object> map = this.jdbcAvicit.getJdbcTemplate().queryForMap(sql);
        String archiveType = (String) map.get("ARCHIVE_TYPE");
        if (!StringUtils.isEmpty(archiveType)) {
            return archiveType;
        } else {
            String id = (String) map.get("PARENT_ID");
            return this.getArchiveTypeByNode(id);
        }
    }

    /**
     * @param formShowList
     * @param migData
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @Title: groupColumnsData
     * @Description:把migData 的值替换到formShowList值中
     * sourceFileTableName  源表名
     * orgId 全宗ID
     * @date 2019-07-27
     * @author HuangJian
     */
    private List<List<Map<String, Object>>> groupColumnsData(String sourceFileTableName, String orgId, List<Map<String, Object>> formShowList, List<Map<String, Object>> migData) throws Exception {
        String dataIdValue = "";
        //存字段类型   字段英文名   字段值
        List<List<Map<String, Object>>> resultList = new ArrayList<>();//最后返回的数据集合
        List<List<Map<String, Object>>> resultFiledList = new ArrayList<>();//最终 数据有多少条 就有多少条formShowList
        if (null != formShowList && migData != null) {
            for (Map<String, Object> dataMap : migData) {//循环多条数据
                List<Map<String, Object>> oneFiledListMapColumn = new ArrayList<>();//第n行的数据列集合
                oneFiledListMapColumn.addAll(formShowList);//把所有的目标列默认复制给oneFiledListMapColumn集合
                migDataFor:
                for (Map.Entry<String, Object> entry1 : dataMap.entrySet()) {
                    String key = entry1.getKey();
                    if ("ID".equalsIgnoreCase(key)) {//ID字段
                        dataIdValue = String.valueOf(entry1.getValue());
                        Map<String, Object> idInfoMap = new HashMap<>();
                        idInfoMap.put("COL_TYPE", "string");
                        idInfoMap.put("COL_NAME", "ID");
                        idInfoMap.put("COL_VALUE", dataIdValue);
                        oneFiledListMapColumn.add(idInfoMap);
                        //break migDataFor;//跳出循环
                    } else {
                        for (Map<String, Object> colListMap : formShowList) {
                            String formColNameKey = (String) colListMap.get("COL_NAME");
                            //key 是源Key  formColNameKey是目标所有的列
                            if (key.equalsIgnoreCase(formColNameKey)) {//如果两个列名相等赋值
                                Object value = entry1.getValue();
                                Iterator<Map.Entry<String, Object>> it = colListMap.entrySet().iterator();
                                Map<String, Object> colListMapTemp = new HashMap<>();
                                //循环key赋值
                                while (it.hasNext()) {//把当前colListMap 复制到colListMapTemp中
                                    Map.Entry<String, Object> entry = it.next();
                                    Object tempKey = entry.getKey();
                                    colListMapTemp.put(tempKey.toString(), colListMap.get(tempKey));
                                }
                                colListMapTemp.put("COL_VALUE", value);//使用之前数据
                                oneFiledListMapColumn.remove(colListMap);//先移除这条字段数据
                                oneFiledListMapColumn.add(colListMapTemp);//在添加有默认值得字段数据
                                break;
                            }
                        }
                    }
                }

                resultFiledList.add(oneFiledListMapColumn);//加入每行的数组字段集合
            }//循环   for (Map<String, Object> dataMap : migData) { 结束
            if (null != resultFiledList && resultFiledList.size() > 0) {
                for (int i = 0; i < resultFiledList.size(); i++) {
                    List<Map<String, Object>> rowFormShowList = resultFiledList.get(i);
                    List<Map<String, Object>> columnList = new ArrayList<Map<String, Object>>();
                    List<Map<String, Object>> result = new ArrayList<>();//最终的结果
                    for (int k = 0; k < rowFormShowList.size(); k++) {
                        Map<String, Object> cc = rowFormShowList.get(k);
                        String colName = (String) cc.get("COL_NAME");
                        //String colLabel = (String) cc.get("COL_LABEL");
                        Map<String, Object> map = new HashMap<>();
                        map.put("COL_TYPE", cc.get("COL_TYPE"));
                        map.put("COL_NAME", cc.get("COL_NAME"));
                        // 判断当前字段是否被设置组合项
                        boolean isSet = false;
                        List<Map<String, Object>> groupColList = new ArrayList<Map<String, Object>>();
                        for (int j = 0; j < columnList.size(); j++) {
                            Map<String, Object> groupCol = columnList.get(j);
                            if (cc.get("ID").equals(groupCol.get("TARGET_COLUMN_ID"))) {
                                isSet = true;
                                groupColList.add(groupCol);
                            }
                        }
                        //下拉类型；0-无，1-参选，2-只选，3-选择(选人，选部门，自定义弹出页)
                        // 参选
                        if ("1".equals(cc.get("COL_DROPDOWN_TYPE"))) {
                            String colValue = (String) cc.get("COL_VALUE");//第一个值
                            if (StringUtils.isEmpty(colValue) || "null".equalsIgnoreCase(colValue)) {//如果第一个值没有数据说明没有默认值
                                continue;
                            }
                            map.put("COL_VALUE", colValue);
                        } else if ("2".equals(cc.get("COL_DROPDOWN_TYPE"))) {//只选
                            String colValue = (String) cc.get("COL_VALUE");//第一个值
                            if (StringUtils.isEmpty(colValue) || "null".equalsIgnoreCase(colValue)) {//如果第一个值没有数据说明没有默认值
                                continue;
                            }
                            map.put("COL_VALUE", colValue);
                        } else if ("3".equals(cc.get("COL_DROPDOWN_TYPE"))) { // 如果为选择
                            String colValue = (String) cc.get("COL_VALUE");//第一个值
                            if (StringUtils.isEmpty(colValue) || "null".equalsIgnoreCase(colValue)) {//如果第一个值没有数据说明没有默认值
                                continue;
                            }
                            //Object col_value_name = cc.get("COL_VALUE_NAME");
                            //Object col_value = cc.get("COL_VALUE");
                            String colId = colName + "_ID";//ID字段
                            //判断migData 是否有key [colId变量] 如果没有直接放弃ID字段 ，如果有  put colId 到result中
                            for (Map<String, Object> migDatumMap : migData) {
                                if (migDatumMap.containsKey(colId)) {
                                    String valueId = (String) migDatumMap.get(colId);
                                    if (!StringUtils.isEmpty(valueId) && !"null".equalsIgnoreCase(valueId)) {
                                        Map idMap = new HashMap();
                                        idMap.put("COL_TYPE", cc.get("COL_TYPE"));
                                        idMap.put("COL_NAME", colId);
                                        idMap.put("COL_VALUE", valueId);
                                        result.add(idMap);
                                        //map.put("COL_VALUE",colValue); 如果ID有 才存name
                                    }
                                }
                            }
                            //String colValueName = (String) cc.get("COL_VALUE_NAME");//第二个值
                            //colName ID对应的中文值字段
                            map.put("COL_VALUE", colValue);//如果ID没有也存name
                        } else if ("2".equals(cc.get("COL_GENE_METHOD"))) {//生成方式；下拉选择：0-空，1-默认值，2-序列，3-顺带，4-组合项，5-统计生成，6-选择
                            //1、查询目标表的最大 保管号  如果这个表

                        } else {
                            if ("integer".equals(cc.get("COL_TYPE"))) {
                                if (null != cc.get("COL_VALUE") && !"null".equals(cc.get("COL_VALUE")) && !"".equals(cc.get("COL_VALUE"))) {
                                    Integer value = Integer.parseInt(String.valueOf(cc.get("COL_VALUE")));
                                    map.put("COL_VALUE", value);
                                } else {
                                    continue;
                                }
                            } else if ("float".equals(cc.get("COL_TYPE"))) {
                                if (null != cc.get("COL_VALUE") && !"null".equals(cc.get("COL_VALUE")) && !"".equals(cc.get("COL_VALUE"))) {
                                    float value = Float.parseFloat(String.valueOf(cc.get("COL_VALUE")));
                                    map.put("COL_VALUE", value);
                                } else {
                                    continue;
                                }
                            } else if ("date".equals(cc.get("COL_TYPE"))) {
                                if (null != cc.get("COL_VALUE") && !"null".equals(cc.get("COL_VALUE")) && !"".equals(cc.get("COL_VALUE"))) {
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    try {
                                        Date colDateValue = sdf.parse(String.valueOf(cc.get("COL_VALUE")));
                                        map.put("COL_VALUE", String.valueOf(cc.get("COL_VALUE")));
                                    } catch (ParseException e) {//如果日期不是到秒
                                        SimpleDateFormat sdfY = new SimpleDateFormat("yyyy-MM-dd");
                                        Date colDateValue = sdfY.parse(String.valueOf(cc.get("COL_VALUE")));
                                        String strDateFormat = sdf.format(colDateValue);
                                        map.put("COL_VALUE", strDateFormat);//格式化好的yyyy-MM-dd HH:mm:ss 日期
                                    }
                                } else {
                                    continue;
                                }
                            } else if ("string".equals(cc.get("COL_TYPE"))) {
                                String replaceValue = "";
                                if (null != cc.get("COL_VALUE") && !"null".equals(cc.get("COL_VALUE")) && !"".equals(cc.get("COL_VALUE"))) {
                                    replaceValue = (String) cc.get("COL_VALUE");
                                    replaceValue = replaceValue.replaceAll("'", "&#39;");
                                    replaceValue = replaceValue.replaceAll("\"", "&#34;");
                                    map.put("COL_VALUE", replaceValue);
                                } else {
                                    continue;
                                }
                            }

                        }
                        if (!map.containsKey("COL_VALUE")) {//如果没有value 直接跳过
                            continue;
                        }
                        result.add(map);
                    }

                    resultList.add(result);//加入每行的数据集合
                }
            }


        }//判断空结束

        return resultList;
    }

    /**
     * 单层文件级根据对应关系 数据迁移
     */
    @SuppressWarnings("rawtypes")
    public void migrationFileDataItera(Map<String, Object> params) throws Exception {
        //8个必填字段值
        String orgId = (String) params.get("orgId");//组织ID
        String deptId = (String) params.get("deptId");//部门ID
        String sysId = (String) params.get("sysId");//系统ID
        String userId = (String) params.get("userId");//当前登陆用户ID
        String ip = (String) params.get("ip");//当前登陆IP地址
        String version = (String) params.get("version");//版本号，默认为 0
        // -----------------批量新增方法--------------
        String sourceFileTableName = (String) params.get("sourceFileTableName");//源表名称
        String tgtFileTableId = (String) params.get("tgtFileTableId");//目标表ID
        String tgtFileTableName = (String) params.get("tgtFileTableName");//目标表名称
        String ids = (String) params.get("ids");//数据ID字符串
        String tgtNodeId = (String) params.get("tgtNodeId");//目标节点ID
        List<Map<String, Object>> fieldsList = (List<Map<String, Object>>) params.get("fileFieldsList");//字段对应信息
        //目标表的所有字段
        List<Map<String, Object>> fieldsListAll = (List<Map<String, Object>>) params.get("fileFieldsListAll");
        System.out.println("开始执行接收-开始批量查询数据集合：" + System.currentTimeMillis());
        //获得需要复制的数据   key:字段  value:数据
        List<Map<String, Object>> migData = getMigrationDataByIds(sourceFileTableName, fieldsList, ids);
        //把源key 替换成 目标的KEY
        List<Map<String, Object>> migDataIter = new ArrayList<>();

        if (null != migData && migData.size() > 0) {
            for (int i = 0; i < migData.size(); i++) {
                Map<String, Object> tempMap = new HashMap<>();
                Map<String, Object> dataMap = migData.get(i);
                for (Map.Entry<String, Object> entry1 : dataMap.entrySet()) {
                    String migDataKey = entry1.getKey();
                    Object migDataValue = entry1.getValue();
                    fieldsDataFor:
                    for (Map<String, Object> fieldsData : fieldsList) {
                        String sourceFieldNameEn = (String) fieldsData.get("SOURCE_FIELD_NAME_EN");//源KEY
                        String tagFieldNameEn = (String) fieldsData.get("TGT_FIELD_NAME_EN");//目标KEY
                        if (sourceFieldNameEn.equals(migDataKey)) {
                            tempMap.put(tagFieldNameEn, migDataValue);
                            break fieldsDataFor;
                        } else if ("ID".equals(migDataKey)) {
                            tempMap.put("ID", migDataValue);
                            break fieldsDataFor;
                        }
                    }
                }
                migDataIter.add(tempMap);
            }
        }
        
        //把migData的数据回填到fieldsListAll 变量的   COL_NAME COL_VAPE
        List<List<Map<String, Object>>> dataResult = groupColumnsData(sourceFileTableName, orgId, fieldsListAll, migDataIter);//多条数据的所有列
        System.out.println("开始执行接收-结束批量查询数据集合：" + System.currentTimeMillis());
        //根据需求拼写SQL查询的字段的值
        StringBuffer getRemarkById = new StringBuffer();
        getRemarkById.append("SELECT REMARK FROM LANTOP_ARCHIVE_CLASS WHERE ID = '");
        getRemarkById.append(tgtNodeId + "'");
        Map<String, Object> remarkValue = this.jdbcAvicit.getJdbcTemplate().queryForMap(getRemarkById.toString());
        if (remarkValue.get("REMARK") != null) {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = sdf1.format(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Map<String, Object> orgMap = new HashMap<>();
            orgMap.put("COL_NAME", "ORG_ID");
            orgMap.put("COL_TYPE", "string");
            orgMap.put("COL_VALUE", orgId);
            Map<String, Object> deptMap = new HashMap<>();
            deptMap.put("COL_NAME", "DEPT_ID");
            deptMap.put("COL_TYPE", "string");
            deptMap.put("COL_VALUE", deptId);
            Map<String, Object> sysIdMap = new HashMap<>();
            sysIdMap.put("COL_NAME", "SYS_ID");
            sysIdMap.put("COL_TYPE", "string");
            sysIdMap.put("COL_VALUE", sysId);
            Map<String, Object> lastByMap = new HashMap<>();
            lastByMap.put("COL_NAME", "LAST_UPDATED_BY");
            lastByMap.put("COL_TYPE", "string");
            lastByMap.put("COL_VALUE", userId);
            Map<String, Object> cDateMap = new HashMap<>();
            cDateMap.put("COL_NAME", "CREATION_DATE");
            cDateMap.put("COL_TYPE", "date");
            cDateMap.put("COL_VALUE", date);
            Map<String, Object> cByMap = new HashMap<>();
            cByMap.put("COL_NAME", "CREATED_BY");
            cByMap.put("COL_TYPE", "string");
            cByMap.put("COL_VALUE", userId);
            Map<String, Object> ipMap = new HashMap<>();
            ipMap.put("COL_NAME", "LAST_UPDATE_IP");
            ipMap.put("COL_TYPE", "string");
            ipMap.put("COL_VALUE", ip);
            Map<String, Object> versionMap = new HashMap<>();
            versionMap.put("COL_NAME", "VERSION");
            versionMap.put("COL_TYPE", "string");
            versionMap.put("COL_VALUE", version);
            Map<String, Object> nodeIdMap = new HashMap<>();
            nodeIdMap.put("COL_NAME", "NODE_ID");
            nodeIdMap.put("COL_TYPE", "string");
            nodeIdMap.put("COL_VALUE", tgtNodeId);
            //归档状态 默认 0整理归档
            Map<String, Object> archiveStatusMap = new HashMap<>();
            archiveStatusMap.put("COL_NAME", "ARCHIVE_STATUS");
            archiveStatusMap.put("COL_TYPE", "string");
            archiveStatusMap.put("COL_VALUE", "0");
            System.out.println("开始执行接收-开始批量复制数据：" + System.currentTimeMillis());
            for (List<Map<String, Object>> dataResultList : dataResult) {
                dataResultList.add(orgMap);
                dataResultList.add(deptMap);
                dataResultList.add(sysIdMap);
                dataResultList.add(lastByMap);
                dataResultList.add(cDateMap);
                dataResultList.add(cByMap);
                dataResultList.add(ipMap);
                dataResultList.add(versionMap);
                dataResultList.add(nodeIdMap);
                dataResultList.add(archiveStatusMap);
                StringBuffer insertSql = new StringBuffer();
                insertSql.append("INSERT INTO " + tgtFileTableName + "(");
                StringBuffer valueSql = new StringBuffer("VALUES (");
                String oldId = "";
                String newId = "";
                boolean ok = false;
                for (Map<String, Object> dataMap : dataResultList) {
                    String colName = String.valueOf(dataMap.get("COL_NAME"));//字段英文名
                    String value = String.valueOf(dataMap.get("COL_VALUE"));//字段值
                    String colType = String.valueOf(dataMap.get("COL_TYPE"));//字段类型
                    insertSql.append("," + colName);
                    if ("ARCHIVE_SHARE_STATUS".equals(colName)) {
                        ok = true;
                    }
                    if (!"ID".equals(colName.toUpperCase())) {
                        if ("string".equals(colType)) {
                            if (value == null || "".equals(value) || "null".equals(value)) {
                                valueSql.append(",''");
                            } else {
                                valueSql.append(",'" + value + "'");
                            }
                        } else if ("integer".equals(colType)) {
                            if (value == null || "".equals(value) || "null".equals(value)) {
                                valueSql.append(",''");
                            } else {
                                valueSql.append("," + Long.valueOf(value));
                            }
                        } else if ("date".equals(colType)) {
                            if (value == null || "".equals(value) || "null".equals(value)) {
                                String currDate = sdf.format(new Date());//如果没有默认当前日期
                                valueSql.append(",TO_DATE('" + currDate + "','yyyy-MM-dd HH24:mi:ss')");
                            } else {
                                int index = value.indexOf(".");
                                if (index > 0) {
                                    value = value.substring(0, index);//去掉日期的小数点
                                }
                                valueSql.append(",TO_DATE('" + value + "','yyyy-MM-dd HH24:mi:ss')");
                            }
                        } else if ("float".equals(colType)) {
                            if (value == null || "".equals(value) || "null".equals(value)) {
                                valueSql.append(",0");
                            } else {
                                valueSql.append("," + Float.valueOf(value));
                            }
                        } else if ("blob".equals(colType)) {
                            if (value == null || "".equals(value) || "null".equals(value)) {
                                valueSql.append(",''");
                            } else {
                                valueSql.append(",'" + value + "'");
                            }
                        } else if ("clob".equals(colType)) {
                            if (value == null || "".equals(value) || "null".equals(value)) {
                                valueSql.append(",''");
                            } else {
                                valueSql.append(",'" + value + "'");
                            }
                        }
                    } else {
                        newId = ComUtil.getId();
                        oldId = value;
                        valueSql.append(",'" + newId + "'");//新ID
                    }
                }
                if (!ok) {//共享状态不存在字段对应中
                    insertSql.append(",ARCHIVE_SHARE_STATUS");
                    valueSql.append(",2");
                }
                valueSql.append(")");
                insertSql.append(")");
                String valueStr = valueSql.toString().replaceFirst(",", "");//列对应的值
                String insertStr = insertSql.toString().replaceFirst(",", "");//列对应的值
                insertStr += "\n" + valueStr;
                jdbcAvicit.getJdbcTemplate().execute(insertStr);
                if (!"".equals(oldId)) {
                    //创建条目附件关系数据
                    Map<String, Object> param = new HashMap<String, Object>();
                    param.put("OLD_RECORD_ID", oldId);
                    param.put("NEW_RECORD_ID", newId);
                    param.put("TABLE_ID", tgtFileTableId);
                    billDefineManagerIntfsService.createAttachmentRelationDatas(param);
                    Map<String, Object> paramMap = new HashMap<String, Object>();
                    paramMap.put("OLD_RECORD_ID", oldId);//归档接口的ID
                    paramMap.put("NEW_RECORD_ID", newId);//整理归档的ID
                    paramMap.put("nodeId",tgtNodeId);
                    paramMap.put("tableId",tgtFileTableId);
                    paramMap.put("orgId",orgId);//组织ID
                    paramMap.put("deptId",deptId);//部门ID
                    paramMap.put("sysId",sysId);//系统ID
                    paramMap.put("userId",userId);//当前登陆用户ID
                    paramMap.put("ip",ip);//当前登陆IP地址
                    paramMap.put("version",version);//版本号，默认为 0
                    paramMap.put("stage","4");
                    paramMap.put("dataType","0");//文件级
                    copyFourResultRelationDatas(paramMap);
                }
            }
            System.out.println("开始执行接收-结束批量复制数据：" + System.currentTimeMillis());
        }
    }


    /**
     * @param params
     * @return void
     * @Title: fileMigrationDataItera
     * @Description:
     * @date 2019-07-27
     * @author HuangJian
     */
    //文件级迁移数据
    private void fileMigrationDataItera(Map<String, Object> params) throws Exception {

        String sysId = (String) params.get("sysId");//系统ID
        String orgId = (String) params.get("orgId");//组织ID
        String deptId = (String) params.get("deptId");//部门ID
        String sourceFileTableId = (String) params.get("sourceFileTableId");//源表ID
        String ids = (String) params.get("ids");//数据ID字符串
        String isRetain = (String) params.get("isRetain");//是否保留原纪录
        //SanXiaFiles update by huangjia 判读在线工作文件真删除
        //onLineSystem === 1：在线归档接收过来的 不保留原纪录的话是 真删除  其他:工作文件过来的 假删除
        String onLineSystem = "";
        if (params.containsKey("onLineSystem")) {
            onLineSystem = (String) params.get("onLineSystem");
        }
        //批量保存数据
        System.out.println("开始执行接收-开始批量保存数据：" + System.currentTimeMillis());
        migrationFileDataItera(params);
        System.out.println("开始执行接收-结束批量保存数据：" + System.currentTimeMillis());
        //删除数据(由于要在文件收集中保留源数据，做假删除)
        if ("1".equals(onLineSystem) && isRetain.equals("no")) {
            String[] strIds = ids.split(",");
            List<String> strList = new ArrayList<String>();
            for (String str : strIds) {
                strList.add(str);
            }

            System.out.println("开始执行接收-开始批量删除数据：" + System.currentTimeMillis());
            // 删除数据
            this.deleteRecordByBatchByIdsListByOnlyDatasByIntfs(orgId, deptId, sysId, sourceFileTableId, strList);
            SysLogUtil.log("鉴定分类模块-在线归档接收", "不保留原始记录{id:" + ids + "}", OpType.delete, OpResult.success, LogBaseFactory.getLogBase());
            billDefineManagerIntfsService.deleteAttachmentByDataIdsByIntfs(strList, sysId);
            System.out.println("开始执行接收-结束批量删除数据：" + System.currentTimeMillis());
        }
    }

    /**
     * 鉴定分类（工作文件接收，在线归档接收 ）共用
     *
     * @param sysId
     * @param orgId
     * @param deptId
     * @param params
     * @param migrationType
     * @return java.lang.String
     * @Title: migrationDataItera
     * @Description: 迁移把目标表默认值写入到数据中
     * @date 2019-07-27
     * @author HuangJian
     */
    @Override
    public String migrationDataItera(String sysId, String orgId, String deptId, Map<String, Object> params, String migrationType) throws Exception {
        String results = "success";
        String sourceNodeId = (String) params.get("sourceNodeId");//源节点ID
        String tableId = (String) params.get("tableId");// 迁移的表ID （源表ID）
        String ip = (String) params.get("ip");// 当前登陆人IP
        String userName = (String) params.get("userName");// 当前登陆用户
        String ids = (String) params.get("ids");//数据id串
        String tgtNodeId = (String) params.get("tgtNodeId");//目标节点ID
        String orgCode = (String) params.get("orgCode");//全宗code
        String languageCode = String.valueOf(params.get("languageCode"));//语言code
        System.out.println("开始执行接收-开始查询字段对应设置表信息：" + System.currentTimeMillis());
        //根据源节点ID获得需要迁移数据节点的源表信息
        Map<String, String> sourceTableDatas = getTableDataByNodeId(orgId, deptId, sysId, sourceNodeId);
        String sourceFileTableId = sourceTableDatas.get("fileTableId");//文件级表ID
        String sourceFileTableName = sourceTableDatas.get("fileTableName");//文件级表名称
        String sourceAnTableId = sourceTableDatas.get("anTableId");//案卷或盒级表ID
        String sourceAnTableName = sourceTableDatas.get("anTableName");//案卷或盒级表名称
        //源表信息暂时存储Map中
        params.put("sourceFileTableId", sourceFileTableId);
        params.put("sourceFileTableName", sourceFileTableName);
        params.put("sourceAnTableId", sourceAnTableId);
        params.put("sourceAnTableName", sourceAnTableName);
        //获得目标节点的表信息
        Map<String, String> tgtTableDatas = getTableDataByNodeId(orgId, deptId, sysId, tgtNodeId);
        String tgtFileTableId = tgtTableDatas.get("fileTableId");//文件级表ID
        String tgtFileTableName = tgtTableDatas.get("fileTableName");//文件级表名称
        String tgtAnTableId = tgtTableDatas.get("anTableId");//案卷或盒级表ID
        String tgtAnTableName = tgtTableDatas.get("anTableName");//案卷或盒级表名称
        //目标表信息暂时存储Map中
        params.put("tgtFileTableId", tgtFileTableId);
        params.put("tgtFileTableName", tgtFileTableName);
        params.put("tgtAnTableId", tgtAnTableId);
        params.put("tgtAnTableName", tgtAnTableName);
        System.out.println("开始执行接收-结束查询字段对应设置表信息：" + System.currentTimeMillis());
        //判断目标文件级表是否存在
        if (tgtFileTableId.equals("") || tgtFileTableName.equals("")) {
            return "souNot";
        }
        //获得字段对应设置，对应字段
        System.out.println("开始执行接收-开始查询字段对应设置字段信息：" + System.currentTimeMillis());
        List<Map<String, Object>> fieldsList = getCorrespondingByTableId1(sourceFileTableId, tgtFileTableId, tgtNodeId, migrationType);
        System.out.println("开始执行接收-结束查询字段对应设置字段信息：" + System.currentTimeMillis());
        params.put("fileFieldsList", fieldsList);

        String userId = (String) params.get("userId");//当前登录人ID
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("currentUserId", userId);//当前用户
        param.put("currentDeptId", deptId);//当前部门
        param.put("currentOrgCode", orgCode);//全宗code
        param.put("nodeId", tgtNodeId);
        param.put("languageCode", languageCode);
        List<Map<String, Object>> addFileFieldList = null;
        String archivechType = getArchiveTypeByNode(tgtNodeId);//2是档案类型
        System.out.println("开始执行接收-开始查询目标表所有字段信息：" + System.currentTimeMillis());
        if ("2".equals(archivechType)) {
            param.put("archiveFlag", "1");//3馆藏，2著录整理  1整理归档
            addFileFieldList = this.billDefineManagerIntfsService.getFieldsByConditionByIntfsItera(orgId, deptId, sysId, tgtFileTableId, "0", "", param);
        } else {
            addFileFieldList = this.billDefineManagerIntfsService.getFieldsByConditionByIntfs(orgId, deptId, sysId, tgtFileTableId, "0", "", param);
        }
        System.out.println("开始执行接收-结束查询目标表所有字段信息：" + System.currentTimeMillis());
        params.put("fileFieldsListAll", addFileFieldList);//目标表的所有字段
        try {
            //文件级迁移接受之前状态修改
            migrationDataStateChange(orgId,deptId,sysId,sourceNodeId,tableId,ip,userName,ids);
            //进行文件级迁移工作
            this.fileMigrationDataItera(params);
        } catch (Exception e){
            results = "failure";
            logger.error("migrationDataItera数据接受异常:"+e.getMessage());
            e.printStackTrace();
        } finally {
            return results;
        }
    }

    /**
     * 数据接受状态修改
     * @param orgId
     * @param deptId
     * @param sysId
     * @param nodeId
     * @param tableId
     * @param ip
     * @param userName
     * @param ids
     * @throws Exception
     */
    private void migrationDataStateChange(String orgId,String deptId,String sysId,String nodeId,String tableId,String ip,String userName,String ids) throws Exception{
        // SanXiaFiles create by zhaoxiaolong 2019/12/12 接收不报错的情况下，更新归档状态为0，0：已接收
        Map<String,Object> updateMap = new HashMap<>();
        updateMap.put("ARCHIVE_STATUS","0");
        updateMap.put("LAST_UPDATE_IP",ip);
        updateMap.put("LAST_UPDATED_BY",userName);
        updateMap.put("LAST_UPDATE_DATE", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        Map<String,Object> parame = new HashMap<>();
        parame.put("modleName","在线归档接收");
        parame.put("markerUpdate","更新归档状态为0");
        String [] updateIdArray = ids.split(",");
        String updateIdArrays = "";
        for (String idValue : updateIdArray){
            updateIdArrays = updateIdArrays + idValue + ";";
        }
        System.out.println("开始执行批量数据更改状态为0-文件级：" + System.currentTimeMillis());
        this.billDefineManagerIntfsService.updateRecordByDataIdsWithUpdateAjByIntfs(orgId, deptId, sysId, nodeId, tableId, updateMap, updateIdArrays, parame);
        System.out.println("结束执行批量数据更改状态为0-文件级：" + System.currentTimeMillis());
    }

    //文件级迁移数据
    private void fileMigrationData(Map<String, Object> params) throws Exception {

        String sysId = (String) params.get("sysId");//系统ID
        String orgId = (String) params.get("orgId");//组织ID
        String deptId = (String) params.get("deptId");//部门ID
        String sourceFileTableId = (String) params.get("sourceFileTableId");//源表ID
        String ids = (String) params.get("ids");//数据ID字符串
        String isRetain = (String) params.get("isRetain");//是否保留原纪录
        //批量保存数据
        migrationFileData(params);
        //删除数据
        if (isRetain.equals("no")) {//不保留
            String[] strIds = ids.split(",");
            List<String> strList = new ArrayList<String>();
            for (String str : strIds) {
                strList.add(str);
            }
            // 删除数据 测试数据
            this.deleteRecordByBatchByIdsListByOnlyDatasByIntfs(orgId, deptId, sysId, sourceFileTableId, strList);
            billDefineManagerIntfsService.deleteAttachmentByDataIdsByIntfs(strList, sysId);
        }

    }

    //案卷级或盒级迁移数据
    private void anMigrationData(Map<String, Object> params) throws Exception {

        String sysId = (String) params.get("sysId");
        String orgId = (String) params.get("orgId");
        String deptId = (String) params.get("deptId");
        String ids = (String) params.get("ids");
        String isRetain = (String) params.get("isRetain");

        //源表表信息
        String sourceFileTableId = (String) params.get("sourceFileTableId");
        String sourceFileTableName = (String) params.get("sourceFileTableName");
        String sourceAnTableId = (String) params.get("sourceAnTableId");

        //批量保存数据
        migrationAnData(params);

        //删除数据
        if (isRetain.equals("no")) {//不保留
            String[] strIds = ids.split(",");
            List<String> strList = new ArrayList<String>();
            for (String str : strIds) {
                strList.add(str);
            }
            // 删除案卷级数据
            this.deleteRecordByBatchByIdsListByOnlyDatasByIntfs(orgId, deptId, sysId, sourceAnTableId, strList);
            billDefineManagerIntfsService.deleteAttachmentByDataIdsByIntfs(strList, sysId);

            //根据案卷IDS，文件表名 获得 文件数据ID集合
            List<String> strFileList = getFileIdByAnId(ids, sourceFileTableName);

            // 删除文件级数据
            this.deleteRecordByBatchByIdsListByOnlyDatasByIntfs(orgId, deptId, sysId, sourceFileTableId, strFileList);
            billDefineManagerIntfsService.deleteAttachmentByDataIdsByIntfs(strFileList, sysId);
        }
    }

    //根据节点获得表id及表名称
    private Map<String, String> getTableDataByNodeId(String orgId, String deptId, String sysId, String nodeId) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String fileTableId = "";
        String fileTableName = "";
        String anTableId = "";
        String anTableName = "";
        //获取数据节点对应关系信息集合
        List<Map<String, Object>> treeNodeIdList = this.commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(orgId, deptId, sysId, nodeId, "");
        if (treeNodeIdList.size() > 0) {
            fileTableId = (String) treeNodeIdList.get(0).get("ID");
            fileTableName = (String) treeNodeIdList.get(0).get("TABLE_NAME");
        }

        //判断数据表关系是一级还是二级
        Map<String, Object> modelParam = new HashMap<String, Object>();
        modelParam.put("treeNodeList", treeNodeIdList);
        Map<String, Object> modelMap = this.archiveClassManagerIntfsService.getDataNodeInfoByParam(modelParam);
        int dataCount = Integer.parseInt(modelMap.get("dataCount").toString());
        if (dataCount == 1) {
            fileTableId = (String) treeNodeIdList.get(0).get("ID");
            fileTableName = (String) treeNodeIdList.get(0).get("TABLE_NAME");
        }
        if (dataCount == 2) {
            anTableId = (String) treeNodeIdList.get(0).get("ID");
            anTableName = (String) treeNodeIdList.get(0).get("TABLE_NAME");
            fileTableId = (String) treeNodeIdList.get(1).get("ID");
            fileTableName = (String) treeNodeIdList.get(1).get("TABLE_NAME");
        }

        map.put("fileTableId", fileTableId);
        map.put("fileTableName", fileTableName);
        map.put("anTableId", anTableId);
        map.put("anTableName", anTableName);

        return map;
    }


    /**
     * 根据两表ID获得字段对应设置中对应字段
     *
     * @param sourceFileTableId
     * @param tgtFileTableId
     * @param tgtNodeId
     * @return List<Map < String, Object>>
     * @author youyu
     */
    private List<Map<String, Object>> getCorrespondingByTableId(String sourceFileTableId, String tgtFileTableId, String tgtNodeId) {

        //获得两表，及目标节点
        StringBuffer queryCount = new StringBuffer();
        queryCount.append("SELECT COUNT(*) NUM \n");
        queryCount.append("  FROM LANTOP_FIELD_RELATE_SET T \n");
        queryCount.append(" WHERE T.SOURCE_TABLE_ID = '" + sourceFileTableId + "' \n");
        queryCount.append("   AND T.TGT_TABLE_ID = '" + tgtFileTableId + "' \n");
        queryCount.append("   AND T.TGT_ARCHIVE_CLASS_ID = '" + tgtNodeId + "' \n");
        queryCount.append("   AND T.ATTRIBUTE_01 = '2' \n");
        queryCount.append("   AND T.ATTRIBUTE_02 = '2' \n");
        int num = this.jdbcAvicit.getJdbcTemplate().queryForObject(queryCount.toString(), Integer.class);
        //判断是否存在有目标节点的两表对应关系
        StringBuffer query = new StringBuffer();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (num > 0) {//有
            query.append("SELECT S.SOURCE_FIELD_NAME_EN, \n");
            query.append("       S.TGT_FIELD_NAME_EN, \n");
            query.append("       S.SOURCE_FIELD_TYPE, \n");
            query.append("       S.TGT_FIELD_TYPE, \n");
            query.append("       T.SOURCE_TABLE_ID, \n");
            query.append("       T.TGT_TABLE_ID, \n");
            query.append("       T.TGT_ARCHIVE_CLASS_ID \n");
            query.append("  FROM LANTOP_FIELD_RELATE_SET_ITEM S \n");
            query.append("  LEFT JOIN LANTOP_FIELD_RELATE_SET T \n");
            query.append("    ON S.LANTOP_FIELD_RELATE_SET_ID = T.ID \n");
            query.append(" WHERE T.SOURCE_TABLE_ID = '" + sourceFileTableId + "' \n");
            query.append("   AND T.TGT_TABLE_ID = '" + tgtFileTableId + "' \n");
            query.append("   AND T.TGT_ARCHIVE_CLASS_ID = '" + tgtNodeId + "' \n");
            query.append("   AND T.ATTRIBUTE_01 = '2' \n");
            query.append("   AND T.ATTRIBUTE_02 = '2' \n");
            list = this.jdbcAvicit.getJdbcTemplate().queryForList(query.toString());

        } else {//没有
            query.append("SELECT S.SOURCE_FIELD_NAME_EN, \n");
            query.append("       S.TGT_FIELD_NAME_EN, \n");
            query.append("       S.SOURCE_FIELD_TYPE, \n");
            query.append("       S.TGT_FIELD_TYPE, \n");
            query.append("       T.SOURCE_TABLE_ID, \n");
            query.append("       T.TGT_TABLE_ID, \n");
            query.append("       T.TGT_ARCHIVE_CLASS_ID \n");
            query.append("  FROM LANTOP_FIELD_RELATE_SET_ITEM S \n");
            query.append("  LEFT JOIN LANTOP_FIELD_RELATE_SET T \n");
            query.append("    ON S.LANTOP_FIELD_RELATE_SET_ID = T.ID \n");
            query.append(" WHERE T.SOURCE_TABLE_ID = '" + sourceFileTableId + "' \n");
            query.append("   AND T.TGT_TABLE_ID = '" + tgtFileTableId + "' \n");
            query.append("   AND T.TGT_ARCHIVE_CLASS_ID IS NULL \n");
            query.append("   AND T.ATTRIBUTE_01 = '2' \n");
            query.append("   AND T.ATTRIBUTE_02 = '2' \n");
            list = this.jdbcAvicit.getJdbcTemplate().queryForList(query.toString());
        }
        return list;
    }


    /**
     * 根据两表ID获得字段对应设置中对应字段    --向明伟
     *
     * @param sourceFileTableId
     * @param tgtFileTableId
     * @param tgtNodeId
     * @return List<Map < String, Object>>
     * @author youyu
     */
    private List<Map<String, Object>> getCorrespondingByTableId1(String sourceFileTableId, String tgtFileTableId, String tgtNodeId, String migrationType) {

        //获得两表，及目标节点
        StringBuffer queryCount = new StringBuffer();
        queryCount.append("SELECT COUNT(*) NUM \n");
        queryCount.append("  FROM LANTOP_FIELD_RELATE_SET T \n");
        queryCount.append(" WHERE T.SOURCE_TABLE_ID = '" + sourceFileTableId + "' \n");
        queryCount.append("   AND T.TGT_TABLE_ID = '" + tgtFileTableId + "' \n");
        queryCount.append("   AND T.TGT_ARCHIVE_CLASS_ID = '" + tgtNodeId + "' \n");
        queryCount.append("   AND T.ATTRIBUTE_01 = '" + migrationType + "' \n");
        queryCount.append("   AND T.ATTRIBUTE_02 = '2' \n");
        int num = this.jdbcAvicit.getJdbcTemplate().queryForObject(queryCount.toString(), Integer.class);
        //判断是否存在有目标节点的两表对应关系
        StringBuffer query = new StringBuffer();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (num > 0) {//有
            query.append("SELECT S.SOURCE_FIELD_NAME_EN, \n");
            query.append("       S.TGT_FIELD_NAME_EN, \n");
            query.append("       S.SOURCE_FIELD_TYPE, \n");
            query.append("       S.TGT_FIELD_TYPE, \n");
            query.append("       T.SOURCE_TABLE_ID, \n");
            query.append("       T.TGT_TABLE_ID, \n");
            query.append("       T.TGT_ARCHIVE_CLASS_ID \n");
            query.append("  FROM LANTOP_FIELD_RELATE_SET_ITEM S \n");
            query.append("  LEFT JOIN LANTOP_FIELD_RELATE_SET T \n");
            query.append("    ON S.LANTOP_FIELD_RELATE_SET_ID = T.ID \n");
            query.append(" WHERE T.SOURCE_TABLE_ID = '" + sourceFileTableId + "' \n");
            query.append("   AND T.TGT_TABLE_ID = '" + tgtFileTableId + "' \n");
            query.append("   AND T.TGT_ARCHIVE_CLASS_ID = '" + tgtNodeId + "' \n");
            query.append("   AND T.ATTRIBUTE_01 = '" + migrationType + "' \n");
            query.append("   AND T.ATTRIBUTE_02 = '2' \n");
            list = this.jdbcAvicit.getJdbcTemplate().queryForList(query.toString());

        } else {//没有
            query.append("SELECT S.SOURCE_FIELD_NAME_EN, \n");
            query.append("       S.TGT_FIELD_NAME_EN, \n");
            query.append("       S.SOURCE_FIELD_TYPE, \n");
            query.append("       S.TGT_FIELD_TYPE, \n");
            query.append("       T.SOURCE_TABLE_ID, \n");
            query.append("       T.TGT_TABLE_ID, \n");
            query.append("       T.TGT_ARCHIVE_CLASS_ID \n");
            query.append("  FROM LANTOP_FIELD_RELATE_SET_ITEM S \n");
            query.append("  LEFT JOIN LANTOP_FIELD_RELATE_SET T \n");
            query.append("    ON S.LANTOP_FIELD_RELATE_SET_ID = T.ID \n");
            query.append(" WHERE T.SOURCE_TABLE_ID = '" + sourceFileTableId + "' \n");
            query.append("   AND T.TGT_TABLE_ID = '" + tgtFileTableId + "' \n");
            query.append("   AND T.TGT_ARCHIVE_CLASS_ID IS NULL \n");
            query.append("   AND T.ATTRIBUTE_01 = '" + migrationType + "' \n");
            query.append("   AND T.ATTRIBUTE_02 = '2' \n");
            list = this.jdbcAvicit.getJdbcTemplate().queryForList(query.toString());
        }
        return list;
    }

    /**
     * 获得目标档案库树结构数据
     */
    @Override
    public List<TreeNode> initDeptFileTree(String tableId, Map<String, Object> param) throws Exception {
        List<TreeNode> datas = this.recurFindTreeNodesByParentId(tableId, "ROOT", param);
        return datas;
    }


    /**
     * 获取树结构信息集合
     *
     * @param tableId
     * @param id
     * @param
     * @param
     * @return
     * @throws Exception List<TreeNode>
     * @throws
     */
    private List<TreeNode> recurFindTreeNodesByParentId(String tableId, String id, Map<String, Object> param) throws Exception {
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        String orgId = param.get("orgId").toString();
        // 查询业务数据   zcl 2019-08-30 控制权限，迁移树形结构只能迁移到本全宗下
        List<Map<String, Object>> childTreeList = findNodesByParentId(tableId, id, orgId);
        try {
            // 将业务数据格式转换成esayui树形格式，此处封装了一个TreeNodeVo节点
            for (Map<String, Object> row : childTreeList) {
                String rid = (String) row.get("id");
                String rname = (String) row.get("archive_class_node_name");
                TreeNode node = new TreeNode();
                node.setId(rid);
                node.setText(rname);
                // 根据节点类型,设置节点图标
                String archiveType = (String) row.get("ARCHIVE_TYPE");
                String nodeType = (String) row.get("ARCHIVE_CLASS_NODE_TYPE");
                String rootId = (String) row.get("PARENT_ID");
                // 根据节点类型,设置节点图标
                if (null != rootId && "ROOT".equals(rootId)) { // 根节点
                    node.setIconCls("icon-im-newnorg");
                } else if (null != archiveType && "-1".equals(archiveType) && null == nodeType) { // 档案类型 -1 物理表
                    node.setIconCls("icon-im-newntable");
                } else if (null != archiveType && "0".equals(archiveType) && null == nodeType) { // 0 模版文件夹
                    node.setIconCls("icon-im-newnmodulefile");
                } else if (null != archiveType && "1".equals(archiveType) && null == nodeType) { // 1 标识文件
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "2".equals(archiveType) && null == nodeType) { // 2 档案
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "3".equals(archiveType) && null == nodeType) { // 3 专题库
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "4".equals(archiveType) && null == nodeType) { // 4 多媒体
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "5".equals(archiveType) && null == nodeType) { // 5 项目归档计划
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "6".equals(archiveType) && null == nodeType) { // 6 管务
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "7".equals(archiveType) && null == nodeType) { // 7 其他
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != archiveType && "10".equals(archiveType) && null == nodeType) { // 10 虚拟表
                    node.setIconCls("icon-im-newnmodulelib");
                } else if (null != nodeType && "1".equals(nodeType)) { // 节点类型 1 文件夹
                    node.setIconCls("icon-im-newnmodulefile");
                } else if (null != nodeType && "2".equals(nodeType)) { // 数据节点
                    node.setIconCls("icon-im-newndatanode");
                    int nodeCount = Integer.parseInt(param.get("nodeCount").toString());
                    nodeCount++;
                    param.put("nodeCount", nodeCount);
                    param.put("nodeId", rid);
                }
                node.setAttributes(row);
                BigDecimal childCount2 = BigDecimal.valueOf(Long.valueOf(row.get("CHILD_COUNT") + ""));
                if (null != childCount2 && childCount2.longValue() > 0) {
                    List<TreeNode> cnodes = recurFindTreeNodesByParentId(tableId, rid, param);
                    node.getChildren().addAll(cnodes);
                    node.setState("open");
                } else {
                    node.setState("open");
                }
                nodes.add(node);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nodes;
    }

    /**
     * 通过父id获取树节点信息集合
     *
     * @param tableId
     * @param parentId
     * @param
     * @param
     * @return
     * @throws Exception List<Map<String,Object>>
     * @throws
     */
    private List<Map<String, Object>> findNodesByParentId(String tableId, String parentId, String orgId) throws Exception {
        Assert.notNull(parentId, "参数不能为空！");
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("WITH T1 AS\n");
        sbSql.append(" (SELECT DISTINCT T.TGT_TABLE_ID,NVL(T.TGT_ARCHIVE_CLASS_ID,'1') AS TGT_ARCHIVE_CLASS_ID\n");
        sbSql.append("    FROM LANTOP_FIELD_RELATE_SET T\n");
        sbSql.append("    LEFT JOIN LANTOP_ARCHIVE_CLASS LAC\n");
        sbSql.append("      ON LAC.ID = T.TGT_ARCHIVE_CLASS_ID\n");
        sbSql.append("   WHERE 1 = 1\n");
        sbSql.append("     AND T.ATTRIBUTE_01 <> '10' AND T.ATTRIBUTE_01 = '2' AND T.ATTRIBUTE_02 = '2'\n");
        sbSql.append("     AND T.SOURCE_TABLE_ID = ?\n");
        sbSql.append("     ),\n");
        sbSql.append("T2 AS\n");
        sbSql.append(" (SELECT CTN.NODE_ID\n");
        sbSql.append("    FROM CBB_TAB_NODE CTN\n");
        sbSql.append("    INNER JOIN LANTOP_ARCHIVE_CLASS LAC\n");
        sbSql.append("      ON LAC.ID = CTN.NODE_ID\n");
        sbSql.append("   INNER JOIN T1\n");
        sbSql.append("   ON CTN.TABLE_ID = T1.TGT_TABLE_ID\n");
        sbSql.append("   WHERE T1.TGT_ARCHIVE_CLASS_ID = '1'\n");
        sbSql.append("   UNION ALL\n");
        sbSql.append("   SELECT T1.TGT_ARCHIVE_CLASS_ID FROM T1 WHERE T1.TGT_ARCHIVE_CLASS_ID <> '1'),\n");
        sbSql.append("T3 AS\n");
        sbSql.append(" (SELECT LAC1.*, SYS_CONNECT_BY_PATH(LAC1.ID, '/') PH\n");
        sbSql.append("    FROM LANTOP_ARCHIVE_CLASS LAC1\n");
        sbSql.append("   WHERE ARCHIVE_CLASS_NODE_CODE NOT IN ('BMWJ', 'GRWJ')\n");
        sbSql.append("  CONNECT BY PRIOR LAC1.ID = LAC1.PARENT_ID\n");
        sbSql.append("   START WITH LAC1.PARENT_ID = 'ROOT'\n");
        sbSql.append("   AND LAC1.ORG_ID = '" + orgId + "'\n");
        sbSql.append("   ORDER BY LAC1.CREATION_DATE ASC, LAC1.NODE_SORT_NUMBER ASC),\n");
        sbSql.append("T4 AS\n");
        sbSql.append(" (SELECT * FROM T3 WHERE T3.ID IN (SELECT * FROM T2)),\n");
        sbSql.append("T5 AS\n");
        sbSql.append(" (SELECT T3.*\n");
        sbSql.append("    FROM T4, T3\n");
        sbSql.append("   WHERE INSTR(T3.PH, T4.ID) > 0\n");
        sbSql.append("  UNION\n");
        sbSql.append("  SELECT T3.* FROM T4, T3 WHERE INSTR(T4.PH, T3.PH) > 0)\n");
        sbSql.append("SELECT (SELECT COUNT(*) FROM T5 T51 WHERE T51.PARENT_ID = T5.ID) CHILD_COUNT, T5.*\n");
        sbSql.append("  FROM T5\n");
        sbSql.append("  WHERE PARENT_ID = ?\n");
        sbSql.append("CONNECT BY PRIOR T5.ID = T5.PARENT_ID\n");
        sbSql.append(" START WITH T5.PARENT_ID = 'ROOT'");
        sbSql.append(" ORDER BY T5.NODE_SORT_NUMBER ASC");
        if (sbSql.length() > 0) {
            list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString(), new Object[]{tableId, parentId});
        }
        return list;
    }


    /**
     * 单层文件级根据对应关系 数据迁移
     */
    @SuppressWarnings("rawtypes")
    public void migrationFileData(Map<String, Object> params) throws Exception {
        //8个必填字段值
        String orgId = (String) params.get("orgId");//组织ID
        String deptId = (String) params.get("deptId");//部门ID
        String sysId = (String) params.get("sysId");//系统ID
        String userId = (String) params.get("userId");//当前登陆用户ID
        String ip = (String) params.get("ip");//当前登陆IP地址
        String version = (String) params.get("version");//版本号，默认为 0
        //zcl 2019-08-31 标识迁移状态  0整理归档  1档案整理
        String archiveStatus = (String) params.get("archiveStatus");
        // -----------------批量新增方法--------------
        String sourceFileTableName = (String) params.get("sourceFileTableName");//源表名称
        String tgtFileTableId = (String) params.get("tgtFileTableId");//目标表ID
        String tgtFileTableName = (String) params.get("tgtFileTableName");//目标表名称
        String ids = (String) params.get("ids");//数据ID字符串
        String tgtNodeId = (String) params.get("tgtNodeId");//目标节点ID
        List<Map<String, Object>> fieldsList = (List<Map<String, Object>>) params.get("fileFieldsList");//字段对应信息
        String sourceNodeId = (String) params.get("sourceNodeId"); // 源节点ID
        // 连接池
        DBConnectionCustomManager connectionMan = null;
        String poolName = orgId + "_" + sysId;
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 实例化连接池
            connectionMan = DBConnectionCustomManager.getInstance(poolName);
            // 获取连接
            conn = connectionMan.getConnection(poolName);// 根据连接池名称从连接池中获取连接
            conn.setAutoCommit(false);

            StringBuffer insertSql = new StringBuffer();
            insertSql.append("INSERT INTO " + tgtFileTableName + "(");
            boolean ok = false;
            //拼接目标表字段
            for (Map<String, Object> fieldsMap : fieldsList) {
                String tgtFieldName = (String) fieldsMap.get("TGT_FIELD_NAME_EN");
                insertSql.append(tgtFieldName + ",");
                if ("ARCHIVE_SHARE_STATUS".equals(tgtFieldName)) {
                    ok = true;
                }
            }
            //拼接固定字段
            insertSql.append("ORG_ID,DEPT_ID,SYS_ID,LAST_UPDATE_DATE,LAST_UPDATED_BY,");
            insertSql.append("CREATION_DATE,CREATED_BY,LAST_UPDATE_IP,");
            insertSql.append("VERSION,NODE_ID,");

            //判断共享状态是否存在字段对应中
            if (!ok) {//共享状态不存在字段对应中
                insertSql.append("ARCHIVE_SHARE_STATUS,");
            }

            insertSql.append("ID,ARCHIVE_STATUS) VALUES (");
            int count = fieldsList.size();
            for (int i = 0; i < count; i++) {
                insertSql.append("?,");
            }
            insertSql.append("?,");//	ORG_ID
            insertSql.append("?,");//	DEPT_ID
            insertSql.append("?,");//	SYS_ID
            insertSql.append("?,");//	LAST_UPDATE_DATE
            insertSql.append("?,");//	LAST_UPDATED_BY
            insertSql.append("?,");//	CREATION_DATE
            insertSql.append("?,");//	CREATED_BY
            insertSql.append("?,");//	LAST_UPDATE_IP
            insertSql.append("?,");//	VERSION
            insertSql.append("?,");//	NODE_ID
            if (!ok) {//共享状态不存在字段对应中
                insertSql.append("?,");//	ARCHIVE_SHARE_STATUS
            }
            insertSql.append("?,");//id
            insertSql.append("?)");//ARCHIVE_STATUS
            ps = conn.prepareStatement(insertSql.toString());
            //获得需要复制的数据
            List<Map<String, Object>> migData = getMigrationDataByIds(sourceFileTableName, fieldsList, ids);

            Iterator iterator;
            for (Map<String, Object> map : migData) {
                iterator = map.keySet().iterator();
                java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
                int index = 1;
                String oldId = "";
                while (iterator.hasNext()) {
                    String colName = String.valueOf(iterator.next());
                    String value = String.valueOf(map.get(colName));
                    // SanXiaFiles create by zhaoxiaolong 获取目标节点的类别号，并重新赋值类别号 start
                    if(colName!=null&&!"".equals(colName)&&"ARCHIVE_CLASSNO".equals(colName)){
                        StringBuffer sbSql = new StringBuffer();
                        sbSql.append("SELECT REMARK FROM LANTOP_ARCHIVE_CLASS WHERE ID IN ('"+tgtNodeId+"')");
                        List<Map<String,Object>> mapList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
                        String remark = ""; // 节点备注
                        if (mapList!=null&&mapList.size()>0){
                            remark = mapList.get(0).get("REMARK").toString();
                        }
                        if (remark!=""){
                            String [] remarkArray = remark.split(";");
                            String archiveClassNoStr = remarkArray[0]; // 类别号
                            archiveClassNoStr = archiveClassNoStr.replace("ARCHIVE_CLASSNO=","");
                            if(archiveClassNoStr!=null&&!"".equals(archiveClassNoStr)){
                                value = archiveClassNoStr;
                            }
                        }
                    }
                    // SanXiaFiles create by zhaoxiaolong 获取目标节点的类别号，并重新赋值类别号 end
                    // SanXiaFiles create by zhaoxiaolong 获取目标节点的类目名称，并重新赋值类目名称 start
                    if(colName!=null&&!"".equals(colName)&&"LMMC".equals(colName)){
                        StringBuffer sbSql = new StringBuffer();
                        sbSql.append("SELECT REMARK FROM LANTOP_ARCHIVE_CLASS WHERE ID IN ('"+tgtNodeId+"')");
                        List<Map<String,Object>> mapList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
                        String remark = ""; // 节点备注
                        if (mapList!=null&&mapList.size()>0){
                            remark = mapList.get(0).get("REMARK").toString();
                        }
                        if (remark!=""){
                            String [] remarkArray = remark.split(";");
                            String archiveClassNoStr = remarkArray[1]; // 类目名称
                            archiveClassNoStr = archiveClassNoStr.replace("LMMC=","");
                            if(archiveClassNoStr!=null&&!"".equals(archiveClassNoStr)){
                                value = archiveClassNoStr;
                            }
                        }
                    }
                    // SanXiaFiles create by zhaoxiaolong 获取目标节点的类目名称，并重新赋值类目名称 end
                    // SanXiaFiles create by zhaoxiaolong 如果档号不包括分类号就不清空档号 start
                    if(colName!=null&&!"".equals(colName)&&"ARCHIVE_CODE".equals(colName)){
                        StringBuffer sbSql = new StringBuffer();
                        sbSql.append("SELECT REMARK FROM LANTOP_ARCHIVE_CLASS WHERE ID IN ('"+sourceNodeId+"')");
                        List<Map<String,Object>> mapList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
                        String remark = ""; // 节点备注
                        if (mapList!=null&&mapList.size()>0){
                            remark = mapList.get(0).get("REMARK").toString();
                        }
                        if (remark!=""){
                            String [] remarkArray = remark.split(";");
                            String archiveClassNoStr = remarkArray[0]; // 类别号
                            archiveClassNoStr = archiveClassNoStr.replace("ARCHIVE_CLASSNO=","");
                            if (value.indexOf(archiveClassNoStr)>0||archiveClassNoStr.indexOf(value)>0){ // 如果档号包含当前类别号，就清空档号
                                value = "";
                            }
                        }
                    }
                    // SanXiaFiles create by zhaoxiaolong 如果档号不包括分类号就不清空档号 end
                    String colType = "string";
                    for (Map<String, Object> fieldsMap : fieldsList) {
                        String sourceFieldName = (String) fieldsMap.get("SOURCE_FIELD_NAME_EN");//源字段名称
                        if (sourceFieldName.equals(colName)) {
                            colType = (String) fieldsMap.get("TGT_FIELD_TYPE");//对应目标字段类型
                            break;
                        }
                    }


                    if (!"ID".equals(colName.toUpperCase())) {
                        if ("ARCHIVE_SHARE_STATUS".equals(colName.toUpperCase())) {
                            //共享状态默认初始值 ‘2’ 已提交
                            ps.setString(index, "2");

                        } else {
                            if ("string".equals(colType)) {
                                if (value == null || "".equals(value) || "null".equals(value)) {
                                    ps.setString(index, "");
                                } else {
                                    ps.setString(index, value);
                                }
                            } else if ("integer".equals(colType)) {
                                if (value == null || "".equals(value) || "null".equals(value)) {
                                    ps.setNull(index, Types.INTEGER);
                                } else {
                                    ps.setLong(index, Long.valueOf(value));
                                }
                            } else if ("date".equals(colType)) {
                                if (value == null || "".equals(value) || "null".equals(value)) {
                                    ps.setNull(index, Types.DATE);
                                } else {
                                    ps.setDate(index, java.sql.Date.valueOf(value.substring(0, 10)));
                                }
                            } else if ("float".equals(colType)) {
                                if (value == null || "".equals(value) || "null".equals(value)) {
                                    ps.setNull(index, Types.FLOAT);
                                } else {
                                    ps.setFloat(index, Float.valueOf(value));
                                }
                            } else if ("blob".equals(colType)) {
                                ps.setNull(index, Types.BLOB);
                            } else if ("clob".equals(colType)) {
                                if (value == null || "".equals(value) || "null".equals(value)) {
                                    ps.setNull(index, Types.CLOB);
                                } else {
                                    ps.setString(index, value);
                                }
                            }
                        }
                        index++;
                    } else {
                        oldId = value;
                    }
                }
                ps.setString(index, orgId);
                index++;
                ps.setString(index, deptId);
                index++;
                ps.setString(index, sysId);
                index++;
                ps.setDate(index, date);
                index++;
                ps.setString(index, userId);
                index++;
                ps.setDate(index, date);
                index++;
                ps.setString(index, userId);
                index++;
                ps.setString(index, ip);
                index++;
                ps.setString(index, version);
                index++;
                ps.setString(index, tgtNodeId);
                index++;
                if (!ok) {//共享状态不存在字段对应中
                    //默认初始值 ‘2’ 已提交
                    ps.setString(index, "2");//	ARCHIVE_SHARE_STATUS
                    index++;
                }
                String id = ComUtil.getId();
                ps.setString(index, id);
                index++;
                ps.setString(index, archiveStatus);
                //sanxiaFiles create by zbj  end 2019.8.21
                ps.addBatch();
                if (!"".equals(oldId)) {
                    //创建条目附件关系数据
                    Map<String, Object> param = new HashMap<String, Object>();
                    param.put("OLD_RECORD_ID", oldId);
                    param.put("NEW_RECORD_ID", id);
                    param.put("TABLE_ID", tgtFileTableId);
                    billDefineManagerIntfsService.createAttachmentRelationDatas(param);
                }
            }
            ps.executeBatch();
            conn.commit();
        } catch (NumberFormatException e) {
            conn.rollback();
            e.printStackTrace();
            throw new Exception("数据转换异常,请检查数据格式！");
        } catch (IllegalArgumentException e) {
            conn.rollback();
            e.printStackTrace();
            throw new Exception("数据转换异常,请检查数据格式！");
        } catch (Exception e) {
            conn.rollback();
            e.printStackTrace();
            throw new Exception("数据库操作异常，请联系管理员！");
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.setAutoCommit(true);
                    connectionMan.deleteConnection(poolName, conn);// 释放，但并未断开连接
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //保存案卷级下文件级数据
    @SuppressWarnings("rawtypes")
    private void migrationFileDatas(Map<String, Object> params) throws Exception {
        //8个必填字段值
        String orgId = (String) params.get("orgId");//组织ID
        String deptId = (String) params.get("deptId");//部门ID
        String sysId = (String) params.get("sysId");//系统ID
        String userId = (String) params.get("userId");//当前登陆用户ID
        String ip = (String) params.get("ip");//当前登陆IP地址
        String version = (String) params.get("version");//版本号，默认为 0
        String archiveStatus = (String) params.get("archiveStatus");//标识迁移状态  0整理归档  1档案整理
        // -----------------批量新增方法--------------
        String tgtFileTableId = (String) params.get("tgtFileTableId");//目标表ID
        String tgtFileTableName = (String) params.get("tgtFileTableName");//目标表名称
        String tgtNodeId = (String) params.get("tgtNodeId");//目标节点ID
        List<Map<String, Object>> fieldsList = (List<Map<String, Object>>) params.get("fileFieldsList");//字段对应信息
        List<Map<String, Object>> anFileData = (List<Map<String, Object>>) params.get("anFileData");
        String anId = "";
        String sourceNodeId = (String) params.get("sourceNodeId"); // 源节点ID
        if (anFileData.size() == 0) {
            return;
        }
        // 连接池
        DBConnectionCustomManager connectionMan = null;
        String poolName = orgId + "_" + sysId;
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 实例化连接池
            connectionMan = DBConnectionCustomManager.getInstance(poolName);
            // 获取连接
            conn = connectionMan.getConnection(poolName);// 根据连接池名称从连接池中获取连接
            conn.setAutoCommit(false);
            for (Map<String, Object> anFileMap : anFileData) {
                anId = (String) anFileMap.get("anId");
                List<Map<String, Object>> fileData = (List<Map<String, Object>>) anFileMap.get("fileData");
//                if (fileData.size() == 0) {
//                    break;
//                }
                StringBuffer insertSql = new StringBuffer();
                insertSql.append("INSERT INTO " + tgtFileTableName + "(");
                boolean ok = false;
                //拼接目标表字段
                for (Map<String, Object> fieldsMap : fieldsList) {
                    String tgtFieldName = (String) fieldsMap.get("TGT_FIELD_NAME_EN");
                    insertSql.append(tgtFieldName + ",");
                    if ("ARCHIVE_SHARE_STATUS".equals(tgtFieldName)) {
                        ok = true;
                    }
                }
                //拼接固定字段
                insertSql.append("ORG_ID,DEPT_ID,SYS_ID,LAST_UPDATE_DATE,LAST_UPDATED_BY,");
                insertSql.append("CREATION_DATE,CREATED_BY,LAST_UPDATE_IP,");
                insertSql.append("VERSION,NODE_ID,PARENT_ID,");
                //SanXiaFiles update by huangjian start 增加ARCHIVE_FLOW_STATUS,ARCHIVE_STATUS
                if(!StringUtil.isEmpty(archiveStatus) && !"null".equalsIgnoreCase(archiveStatus)){
                    insertSql.append("ARCHIVE_FLOW_STATUS,ARCHIVE_STATUS,");
                }
                //SanXiaFiles update by huangjian end
                //判断共享状态是否存在字段对应中
                if (!ok) {//共享状态不存在字段对应中
                    insertSql.append("ARCHIVE_SHARE_STATUS,");
                }

                insertSql.append("ID) VALUES (");
                int count = fieldsList.size();
                for (int i = 0; i < count; i++) {
                    insertSql.append("?,");
                }
                insertSql.append("?,");//	ORG_ID
                insertSql.append("?,");//	DEPT_ID
                insertSql.append("?,");//	SYS_ID
                insertSql.append("?,");//	LAST_UPDATE_DATE
                insertSql.append("?,");//	LAST_UPDATED_BY
                insertSql.append("?,");//	CREATION_DATE
                insertSql.append("?,");//	CREATED_BY
                insertSql.append("?,");//	LAST_UPDATE_IP
                insertSql.append("?,");//	VERSION
                insertSql.append("?,");//	NODE_ID
                insertSql.append("?,");//	PARENT_ID
                //SanXiaFiles update by huangjian start 增加ARCHIVE_FLOW_STATUS,ARCHIVE_STATUS
                if(!StringUtil.isEmpty(archiveStatus) && !"null".equalsIgnoreCase(archiveStatus)){
                    insertSql.append("?,?,");//ARCHIVE_FLOW_STATUS,ARCHIVE_STATUS
                }
                //SanXiaFiles update by huangjian end
                if (!ok) {//共享状态不存在字段对应中
                    insertSql.append("?,");//	ARCHIVE_SHARE_STATUS
                }

                insertSql.append("?)");//id
                ps = conn.prepareStatement(insertSql.toString());

                Iterator iterator;
                for (Map<String, Object> map : fileData) {
                    iterator = map.keySet().iterator();
                    java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
                    int index = 1;
                    String oldId = "";
                    while (iterator.hasNext()) {
                        String colName = String.valueOf(iterator.next());
                        String value = String.valueOf(map.get(colName));
                        String colType = "string";
                        // SanXiaFiles create by zhaoxiaolong 获取目标节点的类别号，并重新赋值类别号 start
                        if(colName!=null&&!"".equals(colName)&&"ARCHIVE_CLASSNO".equals(colName)){
                            StringBuffer sbSql = new StringBuffer();
                            sbSql.append("SELECT REMARK FROM LANTOP_ARCHIVE_CLASS WHERE ID IN ('"+tgtNodeId+"')");
                            List<Map<String,Object>> mapList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
                            String remark = ""; // 节点备注
                            if (mapList!=null&&mapList.size()>0){
                                remark = mapList.get(0).get("REMARK").toString();
                            }
                            if (remark!=""){
                                String [] remarkArray = remark.split(";");
                                String archiveClassNoStr = remarkArray[0]; // 类别号
                                archiveClassNoStr = archiveClassNoStr.replace("ARCHIVE_CLASSNO=","");
                                if(archiveClassNoStr!=null&&!"".equals(archiveClassNoStr)){
                                    value = archiveClassNoStr;
                                }
                            }
                        }
                        // SanXiaFiles create by zhaoxiaolong 获取目标节点的类别号，并重新赋值类别号 end
                        // SanXiaFiles create by zhaoxiaolong 获取目标节点的类目名称，并重新赋值类目名称 start
                        if(colName!=null&&!"".equals(colName)&&"LMMC".equals(colName)){
                            StringBuffer sbSql = new StringBuffer();
                            sbSql.append("SELECT REMARK FROM LANTOP_ARCHIVE_CLASS WHERE ID IN ('"+tgtNodeId+"')");
                            List<Map<String,Object>> mapList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
                            String remark = ""; // 节点备注
                            if (mapList!=null&&mapList.size()>0){
                                remark = mapList.get(0).get("REMARK").toString();
                            }
                            if (remark!=""){
                                String [] remarkArray = remark.split(";");
                                String archiveClassNoStr = remarkArray[1]; // 类目名称
                                archiveClassNoStr = archiveClassNoStr.replace("LMMC=","");
                                if(archiveClassNoStr!=null&&!"".equals(archiveClassNoStr)){
                                    value = archiveClassNoStr;
                                }
                            }
                        }
                        // SanXiaFiles create by zhaoxiaolong 获取目标节点的类目名称，并重新赋值类目名称 end
                        // SanXiaFiles create by zhaoxiaolong 如果档号不包括分类号就不清空档号 start
                        if(colName!=null&&!"".equals(colName)&&"ARCHIVE_CODE".equals(colName)){
                            StringBuffer sbSql = new StringBuffer();
                            sbSql.append("SELECT REMARK FROM LANTOP_ARCHIVE_CLASS WHERE ID IN ('"+sourceNodeId+"')");
                            List<Map<String,Object>> mapList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
                            String remark = ""; // 节点备注
                            if (mapList!=null&&mapList.size()>0){
                                remark = mapList.get(0).get("REMARK").toString();
                            }
                            if (remark!=""){
                                String [] remarkArray = remark.split(";");
                                String archiveClassNoStr = remarkArray[0]; // 类别号
                                archiveClassNoStr = archiveClassNoStr.replace("ARCHIVE_CLASSNO=","");
                                if (value.indexOf(archiveClassNoStr)>0||archiveClassNoStr.indexOf(value)>0){ // 如果档号包含当前类别号，就清空档号
                                    value = "";
                                }
                            }
                        }
                        // SanXiaFiles create by zhaoxiaolong 如果档号不包括分类号就不清空档号 end
                        for (Map<String, Object> fieldsMap : fieldsList) {
                            String sourceFieldName = (String) fieldsMap.get("SOURCE_FIELD_NAME_EN");//源字段名称
                            if (sourceFieldName.equals(colName)) {
                                colType = (String) fieldsMap.get("TGT_FIELD_TYPE");//对应目标字段类型
                                break;
                            }
                        }

                        if (!"ID".equals(colName.toUpperCase())) {
                            if ("ARCHIVE_SHARE_STATUS".equals(colName.toUpperCase())) {
                                //共享状态默认初始值 ‘2’ 已提交
                                ps.setString(index, "2");
                            } else {
                                if ("string".equals(colType)) {
                                    if (value == null || "".equals(value) || "null".equals(value)) {
                                        ps.setString(index, "");
                                    } else {
                                        ps.setString(index, value);
                                    }
                                } else if ("integer".equals(colType)) {
                                    if (value == null || "".equals(value) || "null".equals(value)) {
                                        ps.setNull(index, Types.INTEGER);
                                    } else {
                                        ps.setLong(index, Long.valueOf(value));
                                    }
                                } else if ("date".equals(colType)) {
                                    if (value == null || "".equals(value) || "null".equals(value)) {
                                        ps.setNull(index, Types.DATE);
                                    } else {
                                        ps.setDate(index, java.sql.Date.valueOf(value.substring(0, 10)));
                                    }
                                } else if ("float".equals(colType)) {
                                    if (value == null || "".equals(value) || "null".equals(value)) {
                                        ps.setNull(index, Types.FLOAT);
                                    } else {
                                        ps.setFloat(index, Float.valueOf(value));
                                    }
                                } else if ("blob".equals(colType)) {
                                    ps.setNull(index, Types.BLOB);
                                } else if ("clob".equals(colType)) {
                                    if (value == null || "".equals(value) || "null".equals(value)) {
                                        ps.setNull(index, Types.CLOB);
                                    } else {
                                        ps.setString(index, value);
                                    }
                                }
                            }
                            index++;
                        } else {
                            oldId = value;
                        }
                    }
                    ps.setString(index, orgId);
                    index++;
                    ps.setString(index, deptId);
                    index++;
                    ps.setString(index, sysId);
                    index++;
                    ps.setDate(index, date);
                    index++;
                    ps.setString(index, userId);
                    index++;
                    ps.setDate(index, date);
                    index++;
                    ps.setString(index, userId);
                    index++;
                    ps.setString(index, ip);
                    index++;
                    ps.setString(index, version);
                    index++;
                    ps.setString(index, tgtNodeId);
                    index++;
                    ps.setString(index, anId);
                    index++;
                    //SanXaiFiles update by huangjian start
                    ps.setString(index, "1");//	ARCHIVE_FLOW_STATUS
                    index++;
                    //0整理归档  1档案整理
                    if(!StringUtil.isEmpty(archiveStatus) && !"null".equalsIgnoreCase(archiveStatus)){
                        if(archiveStatus.equals("0")){
                            ps.setString(index, "0");//	ARCHIVE_STATUS
                        }else{
                            ps.setString(index, "1");//	ARCHIVE_STATUS
                        }
                        index++;
                    }
                    //SanXaiFiles update by huangjian end
                    if (!ok) {//共享状态不存在字段对应中
                        //默认初始值 ‘2’ 已提交
                        ps.setString(index, "2");//	ARCHIVE_SHARE_STATUS
                        index++;
                    }

                    String id = ComUtil.getId();
                    ps.setString(index, id);
                    ps.addBatch();
                    if (!"".equals(oldId)) {
                        //创建条目附件关系数据
                        Map<String, Object> param = new HashMap<String, Object>();
                        param.put("OLD_RECORD_ID", oldId);
                        param.put("NEW_RECORD_ID", id);
                        param.put("TABLE_ID", tgtFileTableId);
                        billDefineManagerIntfsService.createAttachmentRelationDatas(param);
                    }


                }
            }
            ps.executeBatch();
            conn.commit();


            /*String updSql = "UPDATE "+tgtFileTableName+" SET ARCHIVE_FLOW_STATUS = '1',ARCHIVE_STATUS = '0' WHERE PARENT_ID = '"+ anId +"\'";
            this.jdbcAvicit.getJdbcTemplate().update(updSql);*/
        } catch (NumberFormatException e) {
            conn.rollback();
            e.printStackTrace();
            throw new Exception("数据转换异常,请检查数据格式！");
        } catch (IllegalArgumentException e) {
            conn.rollback();
            e.printStackTrace();
            throw new Exception("数据转换异常,请检查数据格式！");
        } catch (Exception e) {
            conn.rollback();
            e.printStackTrace();
            throw new Exception("数据库操作异常，请联系管理员！");
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.setAutoCommit(true);
                    connectionMan.deleteConnection(poolName, conn);// 释放，但并未断开连接
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //根据表名，字段信息，父ID获得需要字段对应的数据
    private List<Map<String, Object>> getMigrationDataByParentIds(String sourceFileTableName, List<Map<String, Object>> fieldsList, String id) {
        StringBuffer strSql = new StringBuffer();
        strSql.append("SELECT ");
        //拼接目标表字段
        for (Map<String, Object> fieldsMap : fieldsList) {
            String sourceFieldName = (String) fieldsMap.get("SOURCE_FIELD_NAME_EN");
            strSql.append(sourceFieldName + ",");
        }
        strSql.append("  ID FROM ");
        strSql.append(sourceFileTableName);
        strSql.append(" WHERE PARENT_ID = '" + id + "'");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(strSql.toString());
        return list;
    }

    /**
     * 两层层 案卷或者盒级 根据对应关系 数据迁移
     */
    @SuppressWarnings("rawtypes")
    public void migrationAnData(Map<String, Object> params) throws Exception {
        //8个必填字段值
        String orgId = (String) params.get("orgId");//组织ID
        String deptId = (String) params.get("deptId");//部门ID
        String sysId = (String) params.get("sysId");//系统ID
        String userId = (String) params.get("userId");//当前登陆用户ID
        String ip = (String) params.get("ip");//当前登陆IP
        String version = (String) params.get("version");//版本号 默认0

        String tgtNodeId = (String) params.get("tgtNodeId");//目标节点
        String ids = (String) params.get("ids");//数据ID字符串
        String archiveStatus = (String) params.get("archiveStatus");//标识迁移状态  0整理归档  1档案整理
        //源表信息
        String sourceFileTableName = (String) params.get("sourceFileTableName");//源文件表名称
        String sourceAnTableName = (String) params.get("sourceAnTableName");//源案卷或盒表名称

        //目标表信息
        String tgtAnTableId = (String) params.get("tgtAnTableId");//目标案卷或盒表ID
        String tgtAnTableName = (String) params.get("tgtAnTableName");//目标案卷或盒表名称
        String sourceNodeId = (String) params.get("sourceNodeId"); // 源库表ID
        //字段对应信息
        List<Map<String, Object>> fileFieldsList = (List<Map<String, Object>>) params.get("fileFieldsList");//文件级字段对应信息
        List<Map<String, Object>> anFieldsList = (List<Map<String, Object>>) params.get("anFieldsList");//案卷或盒级字段对应信息

        // -----------------批量新增方法--------------
        // 连接池
        DBConnectionCustomManager connectionMan = null;
        String poolName = orgId + "_" + sysId;
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 实例化连接池
            connectionMan = DBConnectionCustomManager.getInstance(poolName);
            // 获取连接
            conn = connectionMan.getConnection(poolName);// 根据连接池名称从连接池中获取连接
            conn.setAutoCommit(false);

            StringBuffer insertSql = new StringBuffer();
            insertSql.append("INSERT INTO " + tgtAnTableName + "(");
            boolean ok = false;
            //获得需要复制的案卷数据
            //拼接目标案卷级字段
            for (Map<String, Object> anFieldsMap : anFieldsList) {
                String tgtAnFieldName = (String) anFieldsMap.get("TGT_FIELD_NAME_EN");
                insertSql.append(tgtAnFieldName + ",");
                if ("ARCHIVE_SHARE_STATUS".equals(tgtAnFieldName)) {
                    ok = true;
                }
            }

            //拼接固定字段
            insertSql.append("ORG_ID,DEPT_ID,SYS_ID,LAST_UPDATE_DATE,LAST_UPDATED_BY,");
            insertSql.append("CREATION_DATE,CREATED_BY,LAST_UPDATE_IP,");
            insertSql.append("VERSION,NODE_ID,ARCHIVE_FLOW_STATUS,ARCHIVE_STATUS,");

            //判断共享状态是否存在字段对应中
            if (!ok) {//共享状态不存在字段对应中
                insertSql.append("ARCHIVE_SHARE_STATUS,");
            }

            insertSql.append("ID) VALUES (");
            int count = anFieldsList.size();
            for (int i = 0; i < count; i++) {
                insertSql.append("?,");
            }
            insertSql.append("?,");//	ORG_ID
            insertSql.append("?,");//	DEPT_ID
            insertSql.append("?,");//	SYS_ID
            insertSql.append("?,");//	LAST_UPDATE_DATE
            insertSql.append("?,");//	LAST_UPDATED_BY
            insertSql.append("?,");//	CREATION_DATE
            insertSql.append("?,");//	CREATED_BY
            insertSql.append("?,");//	LAST_UPDATE_IP
            insertSql.append("?,");//	VERSION
            insertSql.append("?,");//	NODE_ID
            //2019-10-10 新增流程状态与共享状态
            insertSql.append("?,");//	ARCHIVE_FLOW_STATUS
            insertSql.append("?,");//	ARCHIVE_STATUS

            if (!ok) {//共享状态不存在字段对应中
                insertSql.append("?,");//	ARCHIVE_SHARE_STATUS
            }

            insertSql.append("?)");//id
            ps = conn.prepareStatement(insertSql.toString());
            //迁移的案卷级下文件级数据
            List<Map<String, Object>> anFileData = new ArrayList<Map<String, Object>>();
            //迁移的案卷级数据
            List<Map<String, Object>> migData = getMigrationDataByIds(sourceAnTableName, anFieldsList, ids);
            Iterator iterator;
            for (Map<String, Object> map : migData) {
                iterator = map.keySet().iterator();
                java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
                int index = 1;
                String oldId = "";
                while (iterator.hasNext()) {
                    String colName = String.valueOf(iterator.next());
                    String value = String.valueOf(map.get(colName));
                    String colType = "string";
                    // SanXiaFiles create by zhaoxiaolong 获取目标节点的类别号，并重新赋值类别号 start
                    if(colName!=null&&!"".equals(colName)&&"ARCHIVE_CLASSNO".equals(colName)){
                        StringBuffer sbSql = new StringBuffer();
                        sbSql.append("SELECT REMARK FROM LANTOP_ARCHIVE_CLASS WHERE ID IN ('"+tgtNodeId+"')");
                        List<Map<String,Object>> mapList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
                        String remark = ""; // 节点备注
                        if (mapList!=null&&mapList.size()>0){
                            remark = mapList.get(0).get("REMARK").toString();
                        }
                        if (remark!=""){
                            String [] remarkArray = remark.split(";");
                            String archiveClassNoStr = remarkArray[0]; // 类别号
                            archiveClassNoStr = archiveClassNoStr.replace("ARCHIVE_CLASSNO=","");
                            if(archiveClassNoStr!=null&&!"".equals(archiveClassNoStr)){
                                value = archiveClassNoStr;
                            }
                        }
                    }
                    // SanXiaFiles create by zhaoxiaolong 获取目标节点的类别号，并重新赋值类别号 end
                    // SanXiaFiles create by zhaoxiaolong 获取目标节点的类目名称，并重新赋值类目名称 start
                    if(colName!=null&&!"".equals(colName)&&"LMMC".equals(colName)){
                        StringBuffer sbSql = new StringBuffer();
                        sbSql.append("SELECT REMARK FROM LANTOP_ARCHIVE_CLASS WHERE ID IN ('"+tgtNodeId+"')");
                        List<Map<String,Object>> mapList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
                        String remark = ""; // 节点备注
                        if (mapList!=null&&mapList.size()>0){
                            remark = mapList.get(0).get("REMARK").toString();
                        }
                        if (remark!=""){
                            String [] remarkArray = remark.split(";");
                            String archiveClassNoStr = remarkArray[1]; // 类目名称
                            archiveClassNoStr = archiveClassNoStr.replace("LMMC=","");
                            if(archiveClassNoStr!=null&&!"".equals(archiveClassNoStr)){
                                value = archiveClassNoStr;
                            }
                        }
                    }
                    // SanXiaFiles create by zhaoxiaolong 获取目标节点的类目名称，并重新赋值类目名称 end
                    // SanXiaFiles create by zhaoxiaolong 如果档号不包括分类号就不清空档号 start
                    if(colName!=null&&!"".equals(colName)&&"ARCHIVE_CODE".equals(colName)){
                        StringBuffer sbSql = new StringBuffer();
                        sbSql.append("SELECT REMARK FROM LANTOP_ARCHIVE_CLASS WHERE ID IN ('"+sourceNodeId+"')");
                        List<Map<String,Object>> mapList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
                        String remark = ""; // 节点备注
                        if (mapList!=null&&mapList.size()>0){
                            remark = mapList.get(0).get("REMARK").toString();
                        }
                        if (remark!=""){
                            String [] remarkArray = remark.split(";");
                            String archiveClassNoStr = remarkArray[0]; // 类别号
                            archiveClassNoStr = archiveClassNoStr.replace("ARCHIVE_CLASSNO=","");
                            if (value.indexOf(archiveClassNoStr)>0||archiveClassNoStr.indexOf(value)>0){ // 如果档号包含当前类别号，就清空档号
                                value = "";
                            }
                        }
                    }
                    // SanXiaFiles create by zhaoxiaolong 如果档号不包括分类号就不清空档号 end
                    //获得对应字段类型
                    for (Map<String, Object> fieldsMap : anFieldsList) {
                        String sourceFieldName = (String) fieldsMap.get("SOURCE_FIELD_NAME_EN");//源字段名称
                        if (sourceFieldName.equals(colName)) {
                            colType = (String) fieldsMap.get("TGT_FIELD_TYPE");//对应目标字段类型
                            break;
                        }
                    }
                    if (!"ID".equals(colName.toUpperCase())) {
                        if ("ARCHIVE_SHARE_STATUS".equals(colName.toUpperCase())) {
                            ps.setString(index, "2");
                        } else {
                            if ("string".equals(colType)) {
                                if (value == null || "".equals(value) || "null".equals(value)) {
                                    ps.setString(index, "");
                                } else {
                                    ps.setString(index, value);
                                }
                            } else if ("integer".equals(colType)) {
                                if (value == null || "".equals(value) || "null".equals(value)) {
                                    ps.setNull(index, Types.INTEGER);
                                } else {
                                    ps.setLong(index, Long.valueOf(value));
                                }
                            } else if ("date".equals(colType)) {
                                if (value == null || "".equals(value) || "null".equals(value)) {
                                    ps.setNull(index, Types.DATE);
                                } else {
                                    ps.setDate(index, java.sql.Date.valueOf(value.substring(0, 10)));
                                }
                            } else if ("float".equals(colType)) {
                                if (value == null || "".equals(value) || "null".equals(value)) {
                                    ps.setNull(index, Types.FLOAT);
                                } else {
                                    ps.setFloat(index, Float.valueOf(value));
                                }
                            } else if ("blob".equals(colType)) {
                                ps.setNull(index, Types.BLOB);
                            } else if ("clob".equals(colType)) {
                                if (value == null || "".equals(value) || "null".equals(value)) {
                                    ps.setNull(index, Types.CLOB);
                                } else {
                                    ps.setString(index, value);
                                }
                            }
                        }
                        index++;
                    } else {
                        oldId = value;
                    }
                }
                ps.setString(index, orgId);
                index++;
                ps.setString(index, deptId);
                index++;
                ps.setString(index, sysId);
                index++;
                ps.setDate(index, date);
                index++;
                ps.setString(index, userId);
                index++;
                ps.setDate(index, date);
                index++;
                ps.setString(index, userId);
                index++;
                ps.setString(index, ip);
                index++;
                ps.setString(index, version);
                index++;
                ps.setString(index, tgtNodeId);
                index++;
                //2019-10-10 新增流程状态与共享状态
                ps.setString(index, "1");//	ARCHIVE_FLOW_STATUS
                index++;
                if(archiveStatus!=null){
                    if(archiveStatus.equals("0")){
                        ps.setString(index, "0");//	ARCHIVE_STATUS
                    }else{
                        ps.setString(index, "1");//	ARCHIVE_STATUS
                    }
                    index++;
                }
                if (!ok) {//共享状态不存在字段对应中
                    //默认初始值 ‘2’ 已提交
                    ps.setString(index, "2");//	ARCHIVE_SHARE_STATUS
                    index++;
                }


                String id = ComUtil.getId();
                ps.setString(index, id);
                ps.addBatch();
                if (!"".equals(oldId)) {
                    //创建条目附件关系数据
                    Map<String, Object> param = new HashMap<String, Object>();
                    param.put("OLD_RECORD_ID", oldId);
                    param.put("NEW_RECORD_ID", id);
                    param.put("TABLE_ID", tgtAnTableId);
                    billDefineManagerIntfsService.createAttachmentRelationDatas(param);
                }

                //迁移其名下文件级信息
                String anId = oldId;
                //获得需要复制的文件及数据数据
                List<Map<String, Object>> migFileData = this.getMigrationDataByParentIds(sourceFileTableName, fileFieldsList, anId);

                Map<String, Object> anFileDataMap = new HashMap<String, Object>();
                anFileDataMap.put("anId", id);
                anFileDataMap.put("fileData", migFileData);
                anFileData.add(anFileDataMap);

                /*String updSql = "UPDATE "+sourceFileTableName+" SET ARCHIVE_FLOW_STATUS = '1',ARCHIVE_STATUS = '0' WHERE PARENT_ID = '"+ id +"\'";
                this.jdbcAvicit.getJdbcTemplate().update(updSql);*/

                //迁移文件级数据
                params.put("anFileData", anFileData);
                migrationFileDatas(params);

            }

            ps.executeBatch();
            conn.commit();
        } catch (NumberFormatException e) {
            conn.rollback();
            e.printStackTrace();
            throw new Exception("数据转换异常,请检查数据格式！");
        } catch (IllegalArgumentException e) {
            conn.rollback();
            e.printStackTrace();
            throw new Exception("数据转换异常,请检查数据格式！");
        } catch (Exception e) {
            conn.rollback();
            e.printStackTrace();
            throw new Exception("数据库操作异常，请联系管理员！");
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.setAutoCommit(true);
                    connectionMan.deleteConnection(poolName, conn);// 释放，但并未断开连接
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    //根据表名，字段信息，数据id字符串获得需要字段对应的数据
    private List<Map<String, Object>> getMigrationDataByIds(String sourceFileTableName, List<Map<String, Object>> fieldsList, String ids) {
        StringBuffer strSql = new StringBuffer();
        strSql.append("SELECT ");
        //拼接目标表字段
        for (Map<String, Object> fieldsMap : fieldsList) {
            String sourceFieldName = (String) fieldsMap.get("SOURCE_FIELD_NAME_EN");
            strSql.append(sourceFieldName + ",");
        }
        strSql.append("  ID FROM ");
        strSql.append(sourceFileTableName);
        strSql.append(" WHERE ID IN ('" + ids.replaceAll(",", "','") + "')");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(strSql.toString());
        return list;
    }

    /**
     * 批量删除
     *
     * @param orgId
     * @param deptId
     * @param sysId
     * @param tableId
     * @param ids
     * @throws Exception void
     * @author 钟一华
     */
    public void deleteRecordByBatchByIdsListByOnlyDatasByIntfs(String orgId, String deptId, String sysId, String tableId, List<String> ids) throws Exception {
        if (ids.size() > 0) {
            CbbTables cbbTables = this.getCbbTablesById(tableId);
            // 连接池
            DBConnectionCustomManager connectionMan = null;
            String poolName = orgId + "_" + sysId;
            Connection conn = null;
            PreparedStatement ps = null;
            try {
                // 实例化连接池
                connectionMan = DBConnectionCustomManager.getInstance(poolName);
                // 获取连接
                conn = connectionMan.getConnection(poolName);// 根据连接池名称从连接池中获取连接

                conn.setAutoCommit(false);
                StringBuffer deleteSql = new StringBuffer();
                deleteSql.append("DELETE FROM " + cbbTables.getTableName() + " WHERE ID = ?");
                ps = conn.prepareStatement(deleteSql.toString());
                String recordIds = "";
                for (int i = 0; i < ids.size(); i++) {
                    recordIds += ids.get(i) + ";";
                    ps.setString(1, ids.get(i));
                    ps.addBatch();
                }
                ps.executeBatch();
                conn.commit();
                recordIds = recordIds.substring(0, recordIds.length() - 1);
            } catch (Exception e) {
                conn.rollback();
                e.printStackTrace();
                throw new Exception("数据库操作异常，请联系管理员！");
            } finally {
                if (ps != null) {
                    try {
                        ps.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (conn != null) {
                    try {
                        conn.setAutoCommit(true);
                        connectionMan.deleteConnection(poolName, conn);// 释放，但并未断开连接
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 根据CbbTablesId获取该表对象
     *
     * @param id
     * @return CbbTables
     * @throws
     * @author 朱锋
     */
    public CbbTables getCbbTablesById(String id) {
        CbbTables h = (CbbTables) hibernateDao.getSession().get(CbbTables.class, id);
        return h;
    }

    //根据案卷IDS，文件表名 获得 文件数据ID集合
    private List<String> getFileIdByAnId(String ids, String tableName) {
        String sql = " SELECT ID FROM " + tableName + " WHERE PARENT_ID IN ('" + ids.replaceAll(",", "','") + "')";
        return this.jdbcAvicit.getJdbcTemplate().queryForList(sql, String.class);
    }


    /**
     * @param sysId
     * @param orgId
     * @param deptId
     * @param params
     * @throws Exception 件号调整保存
     * @throws Exception String
     * @throws
     */
    @Override
    public void savePieceNumber(String sysId, String orgId, String deptId,
                                String params, String tableId) throws Exception {

        JSONArray arrayData = JSONArray.fromObject(params);
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Map<String, Object>> mapData = new HashMap<String, Map<String, Object>>();
        for (int i = 0; i < arrayData.size(); i++) {
            String arrayString = arrayData.get(i).toString();
            map = JsonUtils.newInstance().Json2Bean2Form(arrayString, Map.class);
            String id = (String) map.get("ID");
            String archiveInNum = (String) map.get("ARCHIVE_IN_NUM");
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("ARCHIVE_IN_NUM", archiveInNum);
            mapData.put(id, data);
        }
        map = new HashMap<String, Object>();
        map.put("dataMap", mapData);

        billDefineManagerIntfsService.updateRecordByBatchByIntfs(orgId, deptId, sysId, "", tableId, map);
    }


    /**
     * @Author XMW
     * @Description: 获取卷内数据列表数据
     * @Param:
     * @Return:
     */
    @Override
    public Map<String, Object> editArchiveNum(String parentId, String tableId, String nodeId, String openParam, Integer page, Integer rows) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> maps = jdbcAvicit.getJdbcTemplate().queryForList("SELECT TABLE_NAME FROM cbb_tables WHERE ID='" + tableId + "'");
        String tableName = maps.get(0).get("TABLE_NAME") == null ? "" : maps.get(0).get("TABLE_NAME").toString();
        long l = jdbcAvicit.getJdbcTemplate().queryForLong("SELECT count(1) FROM " + tableName + " WHERE PARENT_ID='" + parentId + "'");
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT * FROM (SELECT ROW_.*, ROWNUM ROWNUM_ FROM (SELECT ROW_NUMBER() OVER(ORDER BY NVL(ARCHIVE_IN_NUM,0) ) SORT,T.* FROM ");
        sbSql.append(tableName);
        sbSql.append(" T WHERE PARENT_ID='");
        sbSql.append(parentId + "' ");

        if ("dazl".equals(openParam)) {
        	
        } else {
            sbSql.append(" AND NODE_ID = '" + nodeId + "'  ");
            sbSql.append(" AND ( ARCHIVE_STATUS = '0'  )");
            sbSql.append(" AND ( ARCHIVE_FLOW_STATUS = '1' OR ARCHIVE_FLOW_STATUS = '' OR ARCHIVE_FLOW_STATUS IS NULL )");
            sbSql.append(" AND ARCHIVE_SHARE_STATUS = '2'");
        }
        sbSql.append(" ) ROW_ WHERE ROWNUM <");
        sbSql.append(page * rows + 1);
        sbSql.append(" ) WHERE ROWNUM_ >");
        sbSql.append((page - 1) * rows);
        List<Map<String, Object>> maps1 = jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        resultMap.put("total", l);
        resultMap.put("rows", maps1);
        return resultMap;
    }
    
    /**
     * 调整保管号(件号)
     * @param parentId
     * @param tableId
     * @param nodeId
     * @param openParam
     * @param page
     * @param rows
     * @return 
     * @throws
     */
    @Override
    public Map<String, Object> editZlztBgh(String parentId, String tableId, String nodeId, String openParam, Integer page, Integer rows) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> maps = jdbcAvicit.getJdbcTemplate().queryForList("SELECT TABLE_NAME FROM cbb_tables WHERE ID='" + tableId + "'");
        String tableName = maps.get(0).get("TABLE_NAME") == null ? "" : maps.get(0).get("TABLE_NAME").toString();
        long l = jdbcAvicit.getJdbcTemplate().queryForLong("SELECT count(1) FROM " + tableName + " WHERE NODE_ID='" + nodeId + "' AND (ARCHIVE_STATUS = '0') AND ZLZT = '2'");
    	StringBuffer sbSql = new StringBuffer();
    	sbSql.append("SELECT ID, TM, ZLH, WJH\n");
    	sbSql.append("  FROM (SELECT ROW_.*, ROWNUM ROWNUM_\n");
    	sbSql.append("          FROM (SELECT ID, TM, ZLH, WJH\n");
    	sbSql.append("                  FROM " + tableName + " T\n");
    	sbSql.append("                 WHERE NODE_ID = '" + nodeId + "'\n");
    	sbSql.append("                   AND (ARCHIVE_STATUS = '0')\n");
    	sbSql.append("                   AND ZLZT = '2'\n");
    	sbSql.append("                 ORDER BY ZLH ASC) ROW_\n");
    	sbSql.append("         WHERE ROWNUM < " + (page * rows + 1) + ")\n");
    	sbSql.append(" WHERE ROWNUM_ > " + ((page - 1) * rows)); 
        List<Map<String, Object>> maps1 = jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        resultMap.put("total", l);
        resultMap.put("rows", maps1);
        return resultMap;
    }


    @Override
    public List<Map<String, Object>> getArchivingViewByNodeId(String nodeid, Integer page, Integer rows, String type, String tableName, String lei, String orgCode) throws Exception {
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        StringBuffer sqlbf = new StringBuffer();
        sqlbf.append("SELECT * FROM (SELECT ROW_.*, ROWNUM ROWNUM_  FROM ( SELECT  T.*, LB.START_  FROM  ");
        sqlbf.append(tableName);
        sqlbf.append(" T JOIN (SELECT LFT.ARCHIVE_RCD_ID,B.START_ FROM LANTOP_SUBMIT_ITEM LFT  LEFT JOIN  bpm_hist_procinst B ON LFT.LANTOP_SUBMIT_ID  = B.FORMID_  WHERE B.FORM_CODE_ = '");
        if (lei.equals("3")) {
            sqlbf.append(orgCode + "_" + "WarehousingWorkflow'");
        } else {
            sqlbf.append(orgCode + "_" + "DeptdocarrangeSubmitNew'");
        }
        if (type.equals("1")) {
            sqlbf.append("AND (B.BUSINESSSTATE_='start' OR B.BUSINESSSTATE_ ='active')");
        } else {
            sqlbf.append("AND  B.BUSINESSSTATE_='ended'");
        }
        sqlbf.append(")  LB ON  T.ID=LB.ARCHIVE_RCD_ID  where  NODE_ID = '");
        sqlbf.append(nodeid + "'");
        sqlbf.append(" ORDER BY LB.START_ DESC");
        sqlbf.append(" ) ROW_ WHERE  ROWNUM  <");
        sqlbf.append(page * rows + 1);
        sqlbf.append(" ) WHERE ROWNUM_ >");
        sqlbf.append((page - 1) * rows);

        try {
            mapList = jdbcAvicit.getJdbcTemplate().queryForList(sqlbf.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mapList;
    }

    @Override
    public String getPage(String nodeid, Integer page, Integer rows, String type, String tableName, String lei, String orgCode) throws Exception {
        StringBuffer sqlbf = new StringBuffer();
        sqlbf.append("SELECT COUNT(1)  FROM ");
        sqlbf.append(tableName);
        sqlbf.append(" T JOIN (SELECT LFT.ARCHIVE_RCD_ID,B.START_ FROM LANTOP_SUBMIT_ITEM LFT  LEFT JOIN  bpm_hist_procinst B ON LFT.LANTOP_SUBMIT_ID  = B.FORMID_  WHERE B.FORM_CODE_ = '");
        if (lei.equals("3")) {
            sqlbf.append(orgCode + "_" + "WarehousingWorkflow'");
        } else {
            sqlbf.append(orgCode + "_" + "DeptdocarrangeSubmitNew'");
        }
        if (type.equals("1")) {
            sqlbf.append("AND (B.BUSINESSSTATE_='start' OR B.BUSINESSSTATE_ ='active')");
        } else {
            sqlbf.append("AND  B.BUSINESSSTATE_='ended'");
        }
        sqlbf.append(")  LB ON  T.ID=LB.ARCHIVE_RCD_ID  where  NODE_ID = '");
        sqlbf.append(nodeid + "'");
        //SANXIA DELETE BY QXY START 删除原因:代码规范
//        Long number = 0l;

        Long number = 0L;
        try {
            number = jdbcAvicit.getJdbcTemplate().queryForLong(sqlbf.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return number + "";
    }


    /**
     * @Author XMW
     * @Description: 保存修改后的卷内序号
     * @Param:
     * @Return:
     */
    @Override
    public Map<String, Object> saveArchiveNum(String tableId, String params, String parentId) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("falg", 1);
        resultMap.put("msg", "调整成功!");
        List<Map<String, Object>> maps = jdbcAvicit.getJdbcTemplate().queryForList("SELECT TABLE_NAME FROM cbb_tables WHERE ID='" + tableId + "'");
        String tableName = maps.get(0).get("TABLE_NAME") == null ? "" : maps.get(0).get("TABLE_NAME").toString();
        List<Map<String, Object>> list = jdbcAvicit.getJdbcTemplate().queryForList("SELECT ID,ARCHIVE_IN_NUM FROM  " + tableName + " WHERE PARENT_ID='" + parentId + "' ORDER BY ARCHIVE_IN_NUM");
        Map<String, Object> update1 = new LinkedHashMap<>();
        for (Map<String, Object> map : list) {
            update1.put(map.get("ID") + "", map.get("ARCHIVE_IN_NUM"));
        }
        if (params != null && !"".equals(params)) {
            String[] split = params.split(",");
            for (String s : split) {
                String[] split1 = s.split("-");
                if (split1.length<2){
                    update1.put(split1[0], "-1");
                }else {
                    if (split1[1]==null){
                        update1.put(split1[0], -1);
                    }else {
                        update1.put(split1[0], split1[1]);
                    }
                }
            }
        }
//        List<Object> valueList = new ArrayList<>();
//        for (Map.Entry<String, Object> stringObjectEntry : update1.entrySet()) {
//                valueList.add(stringObjectEntry.getValue());
//        }
//        Collections.sort(valueList);
//        if (valueList.get(0) != 1) {
//            resultMap.put("falg", 2);
//            resultMap.put("msg", "调整的卷内序号不是从1开始不能排序");
//            return resultMap;
//        }
//        for (int i = 1; i < valueList.size(); i++) {
//            if ((valueList.get(i) - valueList.get(i - 1)) != 1) {
//                resultMap.put("falg", 2);
//                resultMap.put("msg", "调整的卷内序号不连续不能排序");
//                return resultMap;
//            }
//        }
        if (params != null && !"".equals(params)) {
            String[] split = params.split(",");
            String temp = "";
            for (String s : split) {
                String[] split1 = s.split("-");

                if (split1.length<2){
                    temp=null;
                }else {
                    temp=split1[1];
                }
                jdbcAvicit.getJdbcTemplate().update("UPDATE " + tableName + " SET ARCHIVE_IN_NUM=" + temp + " WHERE ID='" + split1[0] + "'");
            }
        }
        return resultMap;
    }
    
    /**
     * 保存保管号
     * @param tableId
     * @param params
     * @param parentId
     * @return Map<String,Object>
     * @throws
     */
    @Override
    public Map<String, Object> saveBgh(String tableId, String params, String parentId,String nodeId) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("falg", 1);
        resultMap.put("msg", "调整成功!");
        List<Map<String, Object>> maps = jdbcAvicit.getJdbcTemplate().queryForList("SELECT TABLE_NAME FROM cbb_tables WHERE ID='" + tableId + "'");
        String tableName = maps.get(0).get("TABLE_NAME") == null ? "" : maps.get(0).get("TABLE_NAME").toString();
        if (params != null && !"".equals(params)) {
            String[] split = params.split(",");
            String temp = "";
            for (String s : split) {
                String[] split1 = s.split("-");

                if (split1.length<2){
                    temp=null;
                }else {
                    temp=split1[1];
                }
                jdbcAvicit.getJdbcTemplate().update("UPDATE " + tableName + " SET ZLH=" + temp + " WHERE ID='" + split1[0] + "'");
            }
        }
        return resultMap;
    }


    /**
     * @Author XMW
     * @Description: 卷内序号自动排序
     * @Param:
     * @Return:
     */
    @Override
    public Map<String, Object> autoArchiveSort(String tableId, String sysId, String parentId, String openParam) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("falg", 1);
        resultMap.put("msg", "自动排序成功!");
        List<Map<String, Object>> maps = jdbcAvicit.getJdbcTemplate().queryForList("SELECT TABLE_NAME FROM cbb_tables WHERE ID='" + tableId + "'");
        String tableName = maps.get(0).get("TABLE_NAME") == null ? "" : maps.get(0).get("TABLE_NAME").toString();
        StringBuffer sbSql = new StringBuffer();
        if ("dazl".equals(openParam)) {
            //sbSql.append(" AND  ARCHIVE_STATUS = '1' ");
//            sbSql.append(" AND ( ARCHIVE_FLOW_STATUS = '1' OR ARCHIVE_FLOW_STATUS = '' OR ARCHIVE_FLOW_STATUS IS NULL )");
        } else {
            sbSql.append(" AND ( ARCHIVE_STATUS = '0' OR ARCHIVE_STATUS IS NULL OR ARCHIVE_STATUS = '' )");
            sbSql.append(" AND ( ARCHIVE_FLOW_STATUS = '1' OR ARCHIVE_FLOW_STATUS = '' OR ARCHIVE_FLOW_STATUS IS NULL )");
            sbSql.append(" AND ARCHIVE_SHARE_STATUS = '2'");
        }

        List<Map<String, Object>> list = jdbcAvicit.getJdbcTemplate().queryForList("SELECT ID,ARCHIVE_IN_NUM FROM  " + tableName + " WHERE PARENT_ID='" + parentId + "' " + sbSql.toString() + "  ORDER BY ARCHIVE_IN_NUM");
        for (int i = 0; i < list.size(); i++) {
            int update = jdbcAvicit.getJdbcTemplate().update("UPDATE " + tableName + " SET ARCHIVE_IN_NUM=" + (i + 1) + " WHERE ID='" + list.get(i).get("ID") + "'");
            if (update < 0) {
                resultMap.put("falg", 2);
                resultMap.put("msg", "自动排序失败!");
                return resultMap;
            }
        }

        return resultMap;
    }
    
    /**
     * 保管号自动排序
     * @param tableId
     * @param sysId
     * @param parentId
     * @param openParam
     * @return 
     * @throws
     */
    @Override
    public Map<String, Object> autoBghSort(String tableId, String sysId, String parentId, String openParam,String nodeId) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("falg", 1);
        resultMap.put("msg", "自动调整成功!");
        List<Map<String, Object>> maps = jdbcAvicit.getJdbcTemplate().queryForList("SELECT TABLE_NAME FROM cbb_tables WHERE ID='" + tableId + "'");
        String tableName = maps.get(0).get("TABLE_NAME") == null ? "" : maps.get(0).get("TABLE_NAME").toString();
        StringBuffer sbSql = new StringBuffer();
        sbSql.append(" AND ( ARCHIVE_STATUS = '0' OR ARCHIVE_STATUS IS NULL OR ARCHIVE_STATUS = '' )");
        //sbSql.append(" AND ( ARCHIVE_FLOW_STATUS = '1' OR ARCHIVE_FLOW_STATUS = '' OR ARCHIVE_FLOW_STATUS IS NULL )");
        //sbSql.append(" AND ARCHIVE_SHARE_STATUS = '2'");
        sbSql.append(" AND ZLZT = '2'");
        sbSql.append(" AND NODE_ID = '" + nodeId + "'");
        String sql = "SELECT ID, ZLH FROM  " + tableName + " WHERE 1=1 " + sbSql.toString() + "  ORDER BY ZLH";
        List<Map<String, Object>> list = jdbcAvicit.getJdbcTemplate().queryForList(sql);
        for (int i = 0; i < list.size(); i++) {
            int update = jdbcAvicit.getJdbcTemplate().update("UPDATE " + tableName + " SET ZLH=" + (i + 1) + " WHERE ID='" + list.get(i).get("ID") + "'");
            if (update < 0) {
                resultMap.put("falg", 2);
                resultMap.put("msg", "自动调整失败!");
                return resultMap;
            }
        }

        return resultMap;
    }


    /**
     * 组件功能 修改合并文件的附件
     *
     * @param mergeId
     * @param id
     * @return
     */
    @Override
    public List<String> updateFJRecordId(String mergeId, String id) {
        List<String> resultId = new ArrayList<>();
        List<Map<String, Object>> maps = jdbcAvicit.getJdbcTemplate().queryForList("SELECT\n" +
                "\tR.ID\n" +
                "FROM\n" +
                "\tSYS_ATTACHMENT T\n" +
                "\tLEFT JOIN SYS_USER U ON T.CREATED_BY = U.ID\n" +
                "\tLEFT JOIN CBB_DOC_RELATION R ON T.ID = R.ATTACHMENT_ID \n" +
                "WHERE\n" +
                "\tR.RECORD_ID = '" + mergeId + "' \n" +
                "\tAND R.IF_DELETE = 'N' ");

        if (maps != null && maps.size() > 0) {
            for (Map<String, Object> map : maps) {
                resultId.add(map.get("ID") == null ? null : map.get("ID").toString());
                jdbcAvicit.getJdbcTemplate().update("UPDATE CBB_DOC_RELATION SET RECORD_ID='" + id + "' WHERE ID='" + map.get("ID") + "'");
            }
        } else {
            return null;
        }
        return resultId;
    }


    @Override
    public int closeMerge(String mergeIds, String fjIdsMap, String tableId) {
        int i = 1;
        if (!"".equals(fjIdsMap)) {
            Map<String, Object> map = JSON.parseObject(fjIdsMap, Map.class);
            String[] split = mergeIds.split(";");
            if (split.length > 0) {
                for (String id : split) {
                    List<String> list = map.get(id) == null ? null : (List<String>) map.get(id);
                    if (list != null && list.size() > 0) {
                        for (String s : list) {
                            i = jdbcAvicit.getJdbcTemplate().update("UPDATE CBB_DOC_RELATION SET RECORD_ID='" + id + "' WHERE ID='" + s + "'");
                            if (i < 0) {
                                return i;
                            }
                        }
                    }
                }
            }
        }
        return i;
    }

    @Override
    public List<Map<String, Object>> getDeptDataGridByOrgId(String orgid, String orgName) throws Exception {
        String sql = "";
        if (null != orgName && !orgName.equals("")) {
            sql = "SELECT ID AS DEPTID,OD_NAME AS DEPTNAME,OD_PARENT_ID AS ORGIDENTITY FROM CBB_FONDS_TREE_V WHERE OD_PARENT_ID='" + orgid + "' AND ORG_DEPT_TYPE ='2' AND OD_NAME='" + orgName + "'";
        } else {
            sql = "SELECT ID AS DEPTID,OD_NAME AS DEPTNAME,OD_PARENT_ID AS ORGIDENTITY FROM CBB_FONDS_TREE_V WHERE OD_PARENT_ID='" + orgid + "' AND ORG_DEPT_TYPE ='2'";
        }
        List<Map<String, Object>> list = jdbcAvicit.queryForMap(sql, null);
        return list;
    }


    @Override
    public int fileRecycleSave(String nodeId, String fileId, String tableName, String sysId, String orgId) {

        List<Map<String, Object>> maps = jdbcAvicit.getJdbcTemplate().queryForList("\t\n" +
                "\t\tSELECT ID,COL_NAME,COL_LABEL,COL_TYPE,REMARK FROM  LANTOP_PROJECT_COLUMNS WHERE COL_IS_DISPLAY = 'Y' and COL_IS_TAB_VISIBLE = 'Y' AND TABLE_ID = '" + nodeId + "' \n" +
                "\t\t");
        if (maps != null && maps.size() > 0) {
            //添加工程项目节点id
            Map<String, Object> gcxmjdid = new HashMap<>();
            gcxmjdid.put("COL_NAME", "GCXMJDID");
            gcxmjdid.put("REMARK", nodeId);
            maps.add(gcxmjdid);
            StringBuffer sbsql = new StringBuffer();
//            List<Map<String, Object>> maps1 = jdbcAvicit.getJdbcTemplate().queryForList("select * from " + tableName + " where id='" + fileId + "'");
            StringBuffer sqlSb = new StringBuffer("");
            sqlSb.append(" SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE  \n");
            sqlSb.append("  FROM ALL_TAB_COLS\n ");
            sqlSb.append(" WHERE table_name = '" + tableName + "' \n ");
            //SanXiaFiles update by huangjian  start 增加分组防止字段重复
            sqlSb.append(" GROUP BY \n ");
            sqlSb.append(" TABLE_NAME, COLUMN_NAME, DATA_TYPE ");
            //SanXiaFiles update by huangjian  end
            List<Map<String, Object>> fieldcol = jdbcAvicit.getJdbcTemplate().queryForList(sqlSb.toString());

            sbsql.append("update ");
            sbsql.append(tableName);
            sbsql.append(" set ");
            List<String> str = new ArrayList<>();
            StringBuffer sb1 = new StringBuffer();
            /*for (Map<String, Object> field : fieldcol) {
                mapsFor:for (Map<String, Object> map : maps) {
                    if (map.get("COL_NAME").equals(field.get("COLUMN_NAME"))) {
                        sb1.append(map.get("COL_NAME") + "='");
                        if (map.get("REMARK") == null || "null".equals(map.get("REMARK"))) {
                            sb1.append("'");
                        } else {
                            sb1.append(map.get("REMARK") + "'");
                        }
                        str.add(sb1.toString());
                        sb1.setLength(0);
                        //SanXiaFiles update by huangjian 如果有跳出循环
                        break mapsFor;
                    }
                }

            }*/
            //SanXiaFiles update by huangjain start
            for (Map<String, Object> map : maps) {
                fieldFor:
                for (Map<String, Object> field : fieldcol) {
                    if (map.get("COL_NAME").equals(field.get("COLUMN_NAME"))) {
                        sb1.append(map.get("COL_NAME") + "='");
                        if (map.get("REMARK") == null || "null".equals(map.get("REMARK"))) {
                            sb1.append("'");
                        } else {
                            sb1.append(map.get("REMARK") + "'");
                        }
                        str.add(sb1.toString());
                        sb1.setLength(0);
                        //SanXiaFiles update by huangjian 如果有跳出循环
                        break fieldFor;
                    }
                }

            }
            //SanXiaFiles update by huangjain end
            String[] array = str.toArray(new String[str.size()]);
            String join = StringUtils.join(array, ",");
            sbsql.append(join);
            sbsql.append(" where id='" + fileId + "'");
            int update = jdbcAvicit.getJdbcTemplate().update(sbsql.toString());
            return update;
        } else {
            return 3;
        }
    }


    /**
     * 判断是否属于科研类元数据节点
     *
     * @param kjltablename
     * @return
     */
    @Override
    public Boolean isKJLSourceData(String kjltablename, String fieldName) {
        boolean bool = false;
        if (kjltablename != null && !"".equals(kjltablename)) {
            List<Map<String, Object>> maps = jdbcAvicit.getJdbcTemplate().queryForList("SELECT T.COLUMN_NAME FROM USER_COL_COMMENTS T WHERE T.TABLE_NAME = '" + kjltablename + "' AND t.COLUMN_NAME='" + fieldName + "'");
            if (maps != null && maps.size() > 0) {
                bool = true;
            }
        }
        return bool;
    }

    @Override
    public List<Map<String, Object>> getMAXNUMById(String sysId, String orgId, String deptId, String userId, String type) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT MAX(SUBSTR(SUBMIT_TITILE,greatest( -8,-length(SUBMIT_TITILE)),8)) AS TNUM FROM LANTOP_SUBMIT   WHERE ");
        sql.append("  SUBMIT_USER_ID='" + userId + "' AND");
        sql.append("  ORG_ID='" + orgId + "'AND");
        sql.append("  SYS_ID='" + sysId + "'AND");
        sql.append("  DEPT_ID='" + deptId + "'AND");
        sql.append("  ATTRIBUTE_03='" + type + "'");
        if("1".equals(type)){ //ATTRIBUTE_04为文件归档文书类审批标题序号：归档时采购类，合同类与文书类要排除掉，在查询最大的序号
            sql.append("  AND ATTRIBUTE_04 IS NULL");
        }
        return this.jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
    }

    /**
     * 根据formId修改对应档案的流程状态
     *
     * @param formId
     * @throws Exception
     */
    @Override
    public void updateArchivesStatus(String formId) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT ARCHIVE_TABLE_NAME,ARCHIVE_RCD_ID,ARCHIVE_TABLE_ID from LANTOP_SUBMIT_ITEM WHERE LANTOP_SUBMIT_ID='");
        sql.append(formId + "'");
        List<Map<String, Object>> mapList = this.jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
        if (mapList.get(0).get("ARCHIVE_TABLE_NAME").toString().indexOf("AJJ") > 0) {
            StringBuffer sqlWJName = new StringBuffer();
            sqlWJName.append("SELECT TABLE_NAME  FROM CBB_TABLES WHERE ID IN (SELECT TABLE_ID from CBB_TAB_NODE WHERE NODE_ID in (SELECT NODE_ID FROM CBB_TAB_NODE WHERE TABLE_ID='");
            sqlWJName.append(mapList.get(0).get("ARCHIVE_TABLE_ID").toString());
            sqlWJName.append("' ) AND tab_ORDER='2')");
            List<Map<String, Object>> maps = this.jdbcAvicit.getJdbcTemplate().queryForList(sqlWJName.toString());
            for (int i = 0; i < mapList.size(); i++) {
                StringBuffer sqlAJJ = new StringBuffer();
                sqlAJJ.append("UPDATE ");
                sqlAJJ.append(mapList.get(i).get("ARCHIVE_TABLE_NAME"));
                sqlAJJ.append(" SET ARCHIVE_FLOW_STATUS='1' WHERE ID='");
                sqlAJJ.append(mapList.get(i).get("ARCHIVE_RCD_ID"));
                sqlAJJ.append("'");
                this.jdbcAvicit.getJdbcTemplate().update(sqlAJJ.toString());
                StringBuffer sqlWJJ = new StringBuffer();
                sqlWJJ.append("UPDATE ");
                sqlWJJ.append(maps.get(0).get("TABLE_NAME"));
                sqlWJJ.append(" SET ARCHIVE_FLOW_STATUS='1' WHERE PARENT_ID='");
                sqlWJJ.append(mapList.get(i).get("ARCHIVE_RCD_ID"));
                sqlWJJ.append("'");
                this.jdbcAvicit.getJdbcTemplate().update(sqlWJJ.toString());
            }
        } else {
            for (int i = 0; i < mapList.size(); i++) {
                StringBuffer sqlWJJ = new StringBuffer();
                sqlWJJ.append("UPDATE ");
                sqlWJJ.append(mapList.get(i).get("ARCHIVE_TABLE_NAME"));
                sqlWJJ.append(" SET ARCHIVE_FLOW_STATUS='1' WHERE ID='");
                sqlWJJ.append(mapList.get(i).get("ARCHIVE_RCD_ID"));
                sqlWJJ.append("'");
                this.jdbcAvicit.getJdbcTemplate().update(sqlWJJ.toString());
            }
        }
    }

    /**
     * 根据orgId查询全宗树
     *
     * @param orgId
     * @return
     * @throws Exception
     */
    @Override
    public List<TreeNode> getGeneralArchiveTree(String orgId) throws Exception {
        // 递归一层减一层
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        // 查询业务数据
        List<Map<String, Object>> childTreeList = selectTableFindNodesByParentId(orgId);
        // 将业务数据格式转换成esayui树形格式
        for (Map<String, Object> row : childTreeList) {
            String rid = (String) row.get("ID");
            String rname = (String) row.get("ORG_NAME");
//            String nodeType = (String) row.get("ARCHIVE_CLASS_NODE_TYPE");
            String nodeType = "2";
//            String archiveType = (String) row.get("ARCHIVE_TYPE");
            String archiveType = "-1";
            String parentId = (String) row.get("PARENT_ID");
            TreeNode node = new TreeNode();
            node.setId(rid);
            node.setText(rname);
            // 根据节点类型,设置节点图标
            if (null != parentId && "-1".equals(parentId)) { // 根节点
                node.setIconCls("icon-im-newnorg");
            } else if (null != archiveType && "-1".equals(archiveType)) { // 档案类型
                // -1
                // 物理表
                node.setIconCls("icon-im-newntable");
            } else if (null != archiveType && "0".equals(archiveType)) { // 0
                // 模版文件夹
                node.setIconCls("icon-im-newnmodulefile");
            } else if (null != nodeType && "1".equals(nodeType)) { // 节点类型 1 文件夹
                node.setIconCls("icon-im-newnmodulefile");
            } else if (null != nodeType && "2".equals(nodeType)) { // 数据节点
                node.setIconCls("icon-im-newntable");
            }
            node.setAttributes(row);
            node.set_parentId((String) row.get("PARENT_ID"));
            BigDecimal childCount2 = BigDecimal.valueOf(Long.valueOf(row.get("CHILD_COUNT") + ""));
            if (null != childCount2 && childCount2.longValue() > 0) {
                List<TreeNode> cnodes = getGeneralArchiveTree(rid);
                node.getChildren().addAll(cnodes);
                node.setState("open");
            } else {
                node.setState("open");
            }
            nodes.add(node);
        }
        return nodes;
    }

    /**
     * 获取子节点
     *
     * @param parentId
     * @return
     */
    public List<Map<String, Object>> selectTableFindNodesByParentId(String parentId) {
        Assert.notNull(parentId, "参数不能为空！");
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT ID,ORG_NAME,PARENT_ORG_ID,\n");
        sbSql.append(" COUNT(*)AS CHILD_COUNT \n");
        sbSql.append("  FROM SYS_ORG_V \n");
        sbSql.append(" WHERE PARENT_ORG_ID =");
        sbSql.append("'" + parentId + "'\n");
        sbSql.append("GROUP BY ID,ORG_NAME,PARENT_ORG_ID\n");
        return this.jdbcTemplate.queryForList(sbSql.toString());
    }

    @Override
    public void updateCommission(String formId, String name) throws Exception {
        String sql = "UPDATE CBB_MY_UNDO_APPLY SET APPLY_TITLE='" + name + "' WHERE  FORM_ID='" + formId + "'";
        this.jdbcAvicit.getJdbcTemplate().update(sql);
    }

    @Override
    public String getDeptListByDeptFaId(String deptId, String selectType) throws Exception {
        String sql = "SELECT ID, DEPT_ALIAS, ORG_IDENTITY FROM SYS_DEPT_V WHERE PARENT_DEPT_ID='" + deptId + "' AND DEPT_ALIAS IS NOT NULL   ORDER BY  ORDER_BY ";
        List<Map<String, Object>> mapList = this.jdbcTemplate.queryForList(sql);
        String json = "";
        if (mapList.size() > 0) {
            json += "[";
            for (int i = 0; i < mapList.size(); i++) {
                Map<String, Object> map = new HashMap<>();
                Map<String, Object> maps = new HashMap<>();
                maps.put("nodeType", "dept");
                map.put("id", mapList.get(i).get("ID"));
                map.put("iconCls", "icon-dept");
                map.put("checked", "false");
                map.put("state", "open");
                maps.put("orgIdentity", mapList.get(i).get("ORG_IDENTITY"));
                map.put("attributes", maps);
                map.put("text", mapList.get(i).get("DEPT_ALIAS"));
                String children = getDeptListByDeptFaId(mapList.get(i).get("ID").toString(), selectType);
                if (children.length() > 0) {
                    map.put("children", children);
                } else {
                    map.put("children", null);
                }
                JSONObject jsonObject = JSONObject.fromObject(map);
                if (i < mapList.size() - 1) {
                    json = json + jsonObject + ",";
                } else {
                    json = json + jsonObject;
                }

            }
            json += "]";
        }
        return json;
    }

    @Override
    public List<Map<String, Object>> getTableIdByAnTableId(String tableId) throws Exception {
        String sql = "SELECT DISTINCT TABLE_ID FROM CBB_TAB_NODE WHERE NODE_ID IN (SELECT NODE_ID FROM CBB_TAB_NODE WHERE TABLE_ID='" + tableId + "') AND TAB_ORDER ='2'";
        return this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
    }

    @Override
    public void updateCommissionByOrgId(String formId, String orgId) throws Exception {
        String sql = "UPDATE CBB_MY_UNDO_APPLY SET ATTRIBUTE_08='" + orgId + "' WHERE  FORM_ID='" + formId + "'";
        this.jdbcAvicit.getJdbcTemplate().update(sql);
    }

    /**
     * @param sourceFileTableName 源表名称
     * @param orgId               全宗ID
     * @param formShowList        所有字段集合列
     * @param migData             数据
     * @return java.util.List<java.util.List < java.util.Map < java.lang.String, java.lang.Object>>>
     * @Title: groupColumnsDataInterface
     * @Description: 将所有默认值填充到字段中
     * @date 2019-08-31
     * @author HuangJian
     */
    @Override
    public List<List<Map<String, Object>>> groupColumnsDataInterface(String sourceFileTableName, String orgId, List<Map<String, Object>> formShowList, List<Map<String, Object>> migData) throws Exception {
        return groupColumnsData(sourceFileTableName, orgId, formShowList, migData);
    }

    /**
     * @param migData      数据
     * @param formShowList 所有列的字段集合
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @Title: sourceKeyReplaceTgtKey
     * @Description: 把源对应字段改为目标字段
     * @date 2019-08-31
     * @author HuangJian
     */
    @Override
    public List<Map<String, Object>> sourceKeyReplaceTgtKey(List<Map<String, Object>> migData, List<Map<String, Object>> formShowList) {
        //把源key 替换成 目标的KEY
        List<Map<String, Object>> migDataIter = new ArrayList<>();
        if (null != migData && migData.size() > 0) {
            for (int i = 0; i < migData.size(); i++) {
                Map<String, Object> tempMap = new HashMap<>();
                Map<String, Object> dataMap = migData.get(i);
                for (Map.Entry<String, Object> entry1 : dataMap.entrySet()) {
                    String migDataKey = entry1.getKey();
                    Object migDataValue = entry1.getValue();
                    fieldsDataFor:
                    for (Map<String, Object> fieldsData : formShowList) {
                        String sourceFieldNameEn = (String) fieldsData.get("SOURCE_FIELD_NAME_EN");//源KEY
                        String tagFieldNameEn = (String) fieldsData.get("TGT_FIELD_NAME_EN");//目标KEY
                        if (sourceFieldNameEn.equals(migDataKey)) {
                            tempMap.put(tagFieldNameEn, migDataValue);
                            break fieldsDataFor;
                        } else if ("ID".equals(migDataKey)) {
                            tempMap.put("ID", migDataValue);
                            break fieldsDataFor;
                        }
                    }
                }
                migDataIter.add(tempMap);
            }
        }

        return migDataIter;
    }

    /**
     * @param tgtNodeId      目标节点ID
     * @return List<Map < String, Object>>
     * @Title: addNodeRemarkByTgtNodeId
     * @Description: 把分类树管理的节点 备注字段加入到数据集合中
     * @date 2019-09-01
     * @author HuangJian
     */
    @Override
    public List<List<Map<String, Object>>> addNodeRemarkByTgtNodeId(String tgtNodeId, List<List<Map<String, Object>>> dataResult) {
        //根据需求拼写SQL查询的字段的值
        StringBuffer getRemarkById = new StringBuffer();
        getRemarkById.append("SELECT REMARK FROM LANTOP_ARCHIVE_CLASS WHERE ID = '");
        getRemarkById.append(tgtNodeId + "'");
        Map<String, Object> remarkValue = this.jdbcAvicit.getJdbcTemplate().queryForMap(getRemarkById.toString());
        if (remarkValue.get("REMARK") != null && !"".equals(remarkValue.get("REMARK"))) {
            Map remarkMap = null;
            try {
                //获得需要修改的值，并将要修改的数据转换格式
                String remarkStr = remarkValue.get("REMARK").toString();
                remarkStr = remarkStr.replace("=", "\":\"");
                remarkStr = remarkStr.replace(";", "\",\"");
                remarkStr = "{\"" + remarkStr + "\"}";
                JSONObject jasonObject = JSONObject.fromObject(remarkStr);
                remarkMap = jasonObject;
            } catch (DataAccessException e) {
                return dataResult;
            }

            for (List<Map<String, Object>> dataResultList : dataResult) {
                //标记次数
                int i = 0;
                //标记修改的字段
                List<Object> changedKeyList = new ArrayList<>();
                for (Map<String, Object> changeValue : dataResultList) {
                    for (Object key : remarkMap.keySet()) {
                        if (key.equals(changeValue.get("COL_NAME"))) {
                            changeValue.put("COL_VALUE", remarkMap.get(key));
                            i++;
                            changedKeyList.add(key);
                            break;
                        }

                    }
                    //如果所有字段修改完毕，跳出循环
                    if (i == remarkMap.size()) {
                        break;
                    }
                }
                //若未替换值或替换不完全
                if (remarkMap.size() != i) {
                    //遍历要修改的值
                    for (Object key : remarkMap.keySet()) {
                        //标记是否新加数据
                        boolean isChangedFlag = true;
                        //判断是否有已修改的值
                        if (changedKeyList.size() > 0) {
                            //遍历已修改的值
                            for (Object changedKey : changedKeyList) {
                                if (changedKey.equals(key)) {
                                    isChangedFlag = false;
                                }
                            }
                            if (isChangedFlag) {
                                Map<String, Object> addMap = new HashMap<>();
                                addMap.put("COL_NAME", key);
                                addMap.put("COL_TYPE", "string");
                                addMap.put("COL_VALUE", remarkMap.get(key));
                                dataResultList.add(addMap);
                            }
                        } else {
                            Map<String, Object> addMap = new HashMap<>();
                            addMap.put("COL_NAME", key);
                            addMap.put("COL_TYPE", "string");
                            addMap.put("COL_VALUE", remarkMap.get(key));
                            dataResultList.add(addMap);
                        }
                    }

                }
            }
        }
        return dataResult;
    }

    /**
     * @param dataResult
     * @param param
     * @return java.util.List<java.util.List < java.util.Map < java.lang.String, java.lang.Object>>>
     * @Title: addSysFixColumns
     * @Description: 增加系统固定的字段信息
     * @date 2019-08-31
     * @author HuangJian
     */
    @Override
    public List<List<Map<String, Object>>> addSysFixColumns(List<List<Map<String, Object>>> dataResult, Map<String, Object> param) {
        String orgId = String.valueOf(param.get("orgId"));
        String deptId = String.valueOf(param.get("deptId"));
        String sysId = String.valueOf(param.get("sysId"));
        //String deptId = String.valueOf(param.get("deptId"));
        String userId = String.valueOf(param.get("userId"));
        String ip = String.valueOf(param.get("ip"));
        String version = String.valueOf(param.get("version"));
        String tgtNodeId = String.valueOf(param.get("tgtNodeId"));
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf1.format(System.currentTimeMillis());
        for (List<Map<String, Object>> colList : dataResult) {//加入固定的列名 和 值
            Map<String, Object> orgMap = new HashMap<>();
            orgMap.put("COL_NAME", "ORG_ID");
            orgMap.put("COL_TYPE", "string");
            orgMap.put("COL_VALUE", orgId);
            colList.add(orgMap);

            Map<String, Object> deptMap = new HashMap<>();
            deptMap.put("COL_NAME", "DEPT_ID");
            deptMap.put("COL_TYPE", "string");
            deptMap.put("COL_VALUE", deptId);
            colList.add(deptMap);

            Map<String, Object> sysIdMap = new HashMap<>();
            sysIdMap.put("COL_NAME", "SYS_ID");
            sysIdMap.put("COL_TYPE", "string");
            sysIdMap.put("COL_VALUE", sysId);
            colList.add(sysIdMap);

            Map<String, Object> lastUpdMap = new HashMap<>();
            lastUpdMap.put("COL_NAME", "LAST_UPDATE_DATE");
            lastUpdMap.put("COL_TYPE", "date");
            lastUpdMap.put("COL_VALUE", date);
            colList.add(lastUpdMap);

            Map<String, Object> lastByMap = new HashMap<>();
            lastByMap.put("COL_NAME", "LAST_UPDATED_BY");
            lastByMap.put("COL_TYPE", "string");
            lastByMap.put("COL_VALUE", userId);
            colList.add(lastByMap);

            Map<String, Object> cDateMap = new HashMap<>();
            cDateMap.put("COL_NAME", "CREATION_DATE");
            cDateMap.put("COL_TYPE", "date");
            cDateMap.put("COL_VALUE", date);
            colList.add(cDateMap);

            Map<String, Object> cByMap = new HashMap<>();
            cByMap.put("COL_NAME", "CREATED_BY");
            cByMap.put("COL_TYPE", "string");
            cByMap.put("COL_VALUE", userId);
            colList.add(cByMap);

            Map<String, Object> ipMap = new HashMap<>();
            ipMap.put("COL_NAME", "LAST_UPDATE_IP");
            ipMap.put("COL_TYPE", "string");
            ipMap.put("COL_VALUE", ip);
            colList.add(ipMap);

            Map<String, Object> versionMap = new HashMap<>();
            versionMap.put("COL_NAME", "VERSION");
            versionMap.put("COL_TYPE", "string");
            versionMap.put("COL_VALUE", version);
            colList.add(versionMap);

            Map<String, Object> nodeIdMap = new HashMap<>();
            nodeIdMap.put("COL_NAME", "NODE_ID");
            nodeIdMap.put("COL_TYPE", "string");
            nodeIdMap.put("COL_VALUE", tgtNodeId);
            colList.add(nodeIdMap);

            //归档状态 默认 0整理归档
            Map<String, Object> archiveStatusMap = new HashMap<>();
            archiveStatusMap.put("COL_NAME", "ARCHIVE_STATUS");
            archiveStatusMap.put("COL_TYPE", "string");
            archiveStatusMap.put("COL_VALUE", "0");
            colList.add(archiveStatusMap);
        }
        return dataResult;
    }

    /**
     * @param listMap      需要保存的字段信息集合
     * @param tgtTableName 表英文名称
     * @param tgtTableId   表ID
     * @param fileType     file文件级  an:案卷级
     * @param  sourceTableName 根据表名判断数据来源的系统
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Title: commonSaveAnOrFile
     * @Description: 保存案卷级 或者 卷内件
     * @date 2019-09-01
     * @author HuangJian
     */
    @Override
    public Map<String, Object> commonSaveAnOrFile(List<Map<String, Object>> listMap, String tgtTableName, String tgtTableId, String fileType, String sourceTableName,String orgId) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("status", OpResult.success);
        resultMap.put("des", "");

        StringBuffer insertSql = new StringBuffer();
        insertSql.append("INSERT INTO " + tgtTableName + "(");
        StringBuffer valueSql = new StringBuffer("VALUES (");
        String oldId = "";
        String newId = "";
        String newIdT = "";
        String GJZ ="及用印申请";
        String OrgId = "ORG_ROOT";
        String HT = "LANTOP_HTGLXTGDSJ_WJ";
        boolean ok = false;
        StringBuffer fileIdstr = new StringBuffer();
        for (Map<String, Object> dataMap : listMap) {
            String colName = String.valueOf(dataMap.get("COL_NAME"));//字段英文名
            String value = String.valueOf(dataMap.get("COL_VALUE"));//字段值
            String colType = String.valueOf(dataMap.get("COL_TYPE"));//字段类型
            if ("LAST_UPDATE_DATE".equals(colName)){
                continue;
            }
            insertSql.append("," + colName);
            if ("ARCHIVE_SHARE_STATUS".equals(colName)) {
                ok = true;
            }
            // SanXiaFiles create by zhaoxiaolong 案卷新增时在题名后面加上'的案卷'
            //SanXiaFiles update by huangjian 2019-11-05 卷题名  改为 项目名称字段值 + 的相关资料
            if ("TM".equals(colName)) {
                if (!"file".equalsIgnoreCase(fileType)) {
                    xmmcFor:for (Map<String, Object> temp : listMap) {
                        String colNameTemp = String.valueOf(temp.get("COL_NAME"));//字段英文名
                        String valueTemp = String.valueOf(temp.get("COL_VALUE"));//字段值
                        if("XMMC".equalsIgnoreCase(colNameTemp)){
                            //非招标采购系统归档数据_文件  LANTOP_FZBCGXTGDSJ_1_WJ;招标采购管理系统归档数据_文件  LANTOP_ZBCGGLXTGDSJ_WJ
                            if("LANTOP_FZBCGXTGDSJ_1_WJ".equals(sourceTableName) || "LANTOP_ZBCGGLXTGDSJ_WJ".equals(sourceTableName)){
                                value = valueTemp+"招标采购档案";
                            }else if("LANTOP_HTGLXTGDSJ_WJ".equals(sourceTableName)){  //合同管理系统归档数据_文件  LANTOP_HTGLXTGDSJ_WJ
                                value = valueTemp+"合同签订档案";
                            }else if("LANTOP_OAGLXTGDSJ_0_WJ".equals(sourceTableName)){//OA管理系统归档数据_文件 LANTOP_OAGLXTGDSJ_0_WJ
                                value = valueTemp+"的相关资料";
                            }
                            break xmmcFor;//跳出循环
                        }
                    }

                }
            }
            if (!"ID".equals(colName.toUpperCase())) {
                if ("string".equals(colType)) {
                    if (value == null || "".equals(value) || "null".equals(value)) {
                        valueSql.append(",''");
                    } else {
                        if(fileType == null || "".equals(fileType)){
                            /*如果"fileType"是空说明走的是合同归档不包含"及用印申请"文件级数据*/
                            if(value.indexOf(GJZ) != -1){
                                String valueTT = value.replaceAll(GJZ,"");
                                valueSql.append(",'" + valueTT + "'");
                            }else{
                                valueSql.append(",'" + value + "'");
                            }
                        }else{
                            valueSql.append(",'" + value + "'");
                        }
                    }

                } else if ("integer".equals(colType)) {
                    if (value == null || "".equals(value) || "null".equals(value)) {
                        valueSql.append(",''");
                    } else {
                        valueSql.append("," + Long.valueOf(value));
                    }
                } else if ("date".equals(colType)) {
                    if (value == null || "".equals(value) || "null".equals(value)) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String currDate = sdf.format(new Date());//如果没有默认当前日期
                        valueSql.append(",TO_DATE('" + currDate + "','yyyy-MM-dd HH24:mi:ss')");
                    } else {
                        int index = value.indexOf(".");
                        if (index > 0) {
                            value = value.substring(0, index);//去掉日期的小数点
                        }
                        valueSql.append(",TO_DATE('" + value + "','yyyy-MM-dd HH24:mi:ss')");
                    }
                } else if ("float".equals(colType)) {
                    if (value == null || "".equals(value) || "null".equals(value)) {
                        valueSql.append(",0");
                    } else {
                        valueSql.append("," + Float.valueOf(value));
                    }
                } else if ("blob".equals(colType)) {
                    if (value == null || "".equals(value) || "null".equals(value)) {
                        valueSql.append(",''");
                    } else {
                        valueSql.append(",'" + value + "'");
                    }
                } else if ("clob".equals(colType)) {
                    if (value == null || "".equals(value) || "null".equals(value)) {
                        valueSql.append(",''");
                    } else {
                        valueSql.append(",'" + value + "'");
                    }
                }
            } else {
                if(fileType == null || "".equals(fileType)){
                    /*如果"fileType"说明走的是合同归档不包含"及用印申请"数据*/
                    newIdT = ComUtil.getId();
                    valueSql.append(",'" + newIdT + "'");//新ID
                }else{
                    newId = ComUtil.getId();
                    oldId = value;
                    valueSql.append(",'" + newId + "'");//新ID
                }
            }
//-----------------------------------------------------------------------------------------------------------
            //判断字符串包含"及用印申请"字符并且是合同管理系统归档数据并且是ORG_ROOT登录并且是案卷级别数据
            if (value.indexOf(GJZ) != -1 && HT.equals(sourceTableName) && orgId.equals(OrgId) && "an".equals(fileType)) {
                StringBuffer insertSqlT = new StringBuffer();
                insertSqlT.append("INSERT INTO " + tgtTableName + "(");
                StringBuffer valueSqlT = new StringBuffer("VALUES (");

                for (Map<String, Object> dataMapT : listMap) {
                    String colNameT = String.valueOf(dataMapT.get("COL_NAME"));//字段英文名
                    String valueT = String.valueOf(dataMapT.get("COL_VALUE"));//字段值
                    String colTypeT = String.valueOf(dataMapT.get("COL_TYPE"));//字段类型
                    if ("LAST_UPDATE_DATE".equals(colNameT)) {
                        continue;
                    }
                    insertSqlT.append("," + colNameT);
                    if ("ARCHIVE_SHARE_STATUS".equals(colNameT)) {
                        ok = true;
                    }
                    if (!"ID".equals(colNameT.toUpperCase())) {
                        if ("string".equals(colTypeT)) {
                            if (valueT == null || "".equals(valueT) || "null".equals(valueT)) {
                                valueSqlT.append(",''");
                            } else {
                                if(valueT.indexOf(GJZ) != -1){
                                    String valueTT = valueT.replaceAll(GJZ,"");
                                    valueSqlT.append(",'" + valueTT + "'");
                                }else{
                                    valueSqlT.append(",'" + valueT + "'");
                                }
                            }
                        } else if ("integer".equals(colTypeT)) {
                            if (valueT == null || "".equals(valueT) || "null".equals(valueT)) {
                                valueSqlT.append(",''");
                            } else {
                                valueSqlT.append("," + Long.valueOf(valueT));
                            }
                        } else if ("date".equals(colTypeT)) {
                            if (valueT == null || "".equals(valueT) || "null".equals(valueT)) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String currDate = sdf.format(new Date());//如果没有默认当前日期
                                valueSqlT.append(",TO_DATE('" + currDate + "','yyyy-MM-dd HH24:mi:ss')");
                            } else {
                                int index = valueT.indexOf(".");
                                if (index > 0) {
                                    valueT = valueT.substring(0, index);//去掉日期的小数点
                                }
                                valueSqlT.append(",TO_DATE('" + valueT + "','yyyy-MM-dd HH24:mi:ss')");
                            }
                        } else if ("float".equals(colTypeT)) {
                            if (valueT == null || "".equals(valueT) || "null".equals(valueT)) {
                                valueSqlT.append(",0");
                            } else {
                                valueSqlT.append("," + Float.valueOf(valueT));
                            }
                        } else if ("blob".equals(colTypeT)) {
                            if (valueT == null || "".equals(valueT) || "null".equals(valueT)) {
                                valueSqlT.append(",''");
                            } else {
                                valueSqlT.append(",'" + valueT + "'");
                            }
                        } else if ("clob".equals(colTypeT)) {
                            if (valueT == null || "".equals(valueT) || "null".equals(valueT)) {
                                valueSqlT.append(",''");
                            } else {
                                valueSqlT.append(",'" + valueT + "'");
                            }
                        }
                    } else {
                        newIdT = ComUtil.getId();
                        valueSqlT.append(",'" + newIdT + "'");//新ID
                    }
                }
                if (!ok) {//共享状态不存在字段对应中
                    insertSqlT.append(",ARCHIVE_SHARE_STATUS");
                    valueSqlT.append(",2");
                }
                valueSqlT.append(",1");
                valueSqlT.append(")");
                insertSqlT.append(",ARCHIVE_FLOW_STATUS");
                insertSqlT.append(")");
                String valueStrT = valueSqlT.toString().replaceFirst(",", "");//列对应的值
                String insertStrT = insertSqlT.toString().replaceFirst(",", "");//列对应的值
                insertStrT += "\n" + valueStrT;
                jdbcAvicit.getJdbcTemplate().execute(insertStrT);
            }
        }
//-----------------------------------------------------------------------------------------------------------
        if (!ok) {//共享状态不存在字段对应中
            insertSql.append(",ARCHIVE_SHARE_STATUS");
            valueSql.append(",2");
        }
        valueSql.append(",1");
        valueSql.append(")");
        insertSql.append(",ARCHIVE_FLOW_STATUS");
        insertSql.append(")");
        String valueStr = valueSql.toString().replaceFirst(",", "");//列对应的值
        String insertStr = insertSql.toString().replaceFirst(",", "");//列对应的值
        insertStr += "\n" + valueStr;
        String strFlag = "案卷级";
        if ("file".equalsIgnoreCase(fileType)) {
            strFlag = "文件级";
        }
        if(fileType == null || "".equals(fileType)){
            /*如果"fileType"说明走的是合同归档不包含"及用印申请"数据*/
            resultMap.put("fileIdsT",newIdT);
        }else{
            resultMap.put("fileIds",newId);
        }
        try {
            jdbcAvicit.getJdbcTemplate().execute(insertStr);
            if ("file".equalsIgnoreCase(fileType)) {//如果是案卷级增加附件信息
                //SanXiaFiles add by huanjgian start 返回文件级 或卷内件新ID和旧Id
                resultMap.put("FILE_OLD_RECORD_ID",oldId);
                resultMap.put("FILE_NEW_RECORD_ID",newId);
                //SanXiaFiles add by huanjgian end
                if (!"".equals(oldId)) {
                    //创建条目附件关系数据
                    Map<String, Object> param = new HashMap<String, Object>();
                    param.put("OLD_RECORD_ID", oldId);
                    param.put("NEW_RECORD_ID", newId);
                    param.put("TABLE_ID", tgtTableId);
                    billDefineManagerIntfsService.createAttachmentRelationDatas(param);
                }
            }else if("".equals(fileType) || fileType == null){
                resultMap.put("FILE_OLD_RECORD_ID",oldId);
                resultMap.put("FILE_NEW_RECORD_IDT",newIdT);
            } else {
                resultMap.put("anId", newId);//案卷级新ID
                resultMap.put("anIdT", newIdT);//案卷级新ID
            }
        } catch (DataAccessException e) {
            resultMap.put("status", OpResult.failure);
            resultMap.put("des", "数据库操作异常，请联系管理员！");
        } catch (Exception e) {//保存附件异常
            resultMap.put("status", OpResult.failure);
            resultMap.put("des", "数据库操作异常，请联系管理员！");
        }
        return resultMap;
    }

    /**
    * @Title: copyFourResultRelationDatas 
    * @Description:  
    * @param params
    * @return void
    * @date 2020-01-15 
    * @author HuangJian
    */
    @Override
    public Map<String,Object> copyFourResultRelationDatas(Map<String,Object> params) throws Exception{

        //----------------------参数
        String orgId = (String) params.get("orgId");//组织ID
        String deptId = (String) params.get("deptId");//部门ID
        String sysId = (String) params.get("sysId");//系统ID
        String userId = (String) params.get("userId");//当前登陆用户ID
        String ip = (String) params.get("ip");//当前登陆IP地址
        String version = (String) params.get("version");//版本号，默认为 0

        String  oldId = String.valueOf(params.get("OLD_RECORD_ID"));//归档接口的ID
        String recordId = String.valueOf(params.get("NEW_RECORD_ID"));//整理归档的ID
        String nodeId = (String) params.get("nodeId");
        String tableId = (String) params.get("tableId");
        String stage = (String) params.get("stage");//阶段 1整理归档 2档案整理 3档案保管 4接口归档 5离线客户端 6跨全宗移交
        String dataType = (String) params.get("dataType");//0文件级 1案卷级  2卷内件
        //---------------------

        //SanXiaFiles add by huangjian 2020-01-15 把接口归档的四性检测 复制一份 给整理归档
        //1、查询归档接口 OLD_RECORD_ID  复制给 NEW_RECORD_ID
        StringBuffer sbSql = new StringBuffer("");
        sbSql.append("SELECT R.ID FROM LANTOP_FOURCHECKED R WHERE R.RECORD_ID = '"+oldId+"' AND R.STAGE = '"+stage+"' \n");
        List<Map<String, Object>> isExitsList = jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        if(null != isExitsList && isExitsList.size() > 0){//有四性检测结果
            String interfaceMastId = String.valueOf(isExitsList.get(0).get("ID"));//归档接口的主表ID
            String mastId = ComUtil.getId();
            StringBuffer colSql = new StringBuffer();
            StringBuffer valuesSql = new StringBuffer();
            //插入主表记录
            colSql.append("INSERT INTO LANTOP_FOURCHECKED (");

            colSql.append("ID,RECORD_ID,ORG_ID,NODE_ID,STAGE,DATA_TYPE,TABLE_ID,DEPT_ID,SYS_ID,");
            colSql.append("LAST_UPDATE_DATE,LAST_UPDATED_BY,CREATION_DATE,CREATED_BY,LAST_UPDATE_IP,VERSION)");
            valuesSql.append("VALUES (  ");
            valuesSql.append(" '" + mastId + "','" + recordId + "','" + orgId + "','" + nodeId + "','" + stage + "','" + dataType + "','" + tableId + "','" + deptId + "','" + sysId + "'   ");
            valuesSql.append(" ,sysdate,'" + userId + "'  ");
            valuesSql.append("  ,sysdate,'" + userId + "','" + ip + "','" + version + "')  ");

            String mastSql = colSql.toString() + valuesSql.toString();
            logger.info("新增主表四性检测："+mastSql);
            try {
                jdbcAvicit.getJdbcTemplate().execute(mastSql);

                //查询归档接口子表是否存在
                StringBuffer sbSqlFrom = new StringBuffer("");
                sbSqlFrom.append("SELECT * FROM LANTOP_FOURCHECKED_RESULT R WHERE R.FOURCHECKED_RESULT_ID = '"+interfaceMastId+"' ");
                List<Map<String, Object>> fromListMap = jdbcAvicit.getJdbcTemplate().queryForList(sbSqlFrom.toString());
                if(null != fromListMap && fromListMap.size() > 0){
                    Map<String, Object> fourResultOne = fromListMap.get(0);

                    //排除的字段
                    String notColumn = "ID,FOURCHECKED_RESULT_ID,LAST_UPDATE_DATE,LAST_UPDATED_BY,CREATION_DATE,CREATED_BY,LAST_UPDATE_IP,VERSION";

                    StringBuffer insertSqlStr = new StringBuffer("");
                    StringBuffer valuesSqlStr = new StringBuffer();
                    insertSqlStr.append("INSERT INTO LANTOP_FOURCHECKED_RESULT (");
                    valuesSqlStr.append(" VALUES ( ");
                    Set<Map.Entry<String, Object>> entrySet = fourResultOne.entrySet();
                    Iterator<Map.Entry<String, Object>> iter = entrySet.iterator();
                    while (iter.hasNext()){
                        Map.Entry<String, Object> entry = iter.next();
                        String key = entry.getKey();
                        String value = String.valueOf(entry.getValue());
                        if(notColumn.indexOf(key) == -1){
                            insertSqlStr.append( key+",");
                            if("null".equalsIgnoreCase(value)){
                                value = "";
                            }
                            valuesSqlStr.append("'" + value + "', ");
                        }else{

                        }
                    }
                    String fromNewId = ComUtil.getId();
                    insertSqlStr.append("  ID,FOURCHECKED_RESULT_ID,");
                    insertSqlStr.append(" LAST_UPDATE_DATE,LAST_UPDATED_BY,CREATION_DATE,CREATED_BY,LAST_UPDATE_IP,VERSION ) ");

                    valuesSqlStr.append(" '" + fromNewId + "','" + mastId + "',  ");
                    //固定字段值
                    valuesSqlStr.append(" sysdate,'" + userId + "'  ");
                    valuesSqlStr.append("  ,sysdate,'" + userId + "','" + ip + "','" + version + "')  ");
                    String fromSql = insertSqlStr.toString() + valuesSqlStr.toString();
                    try {
                        jdbcAvicit.getJdbcTemplate().execute(fromSql);
                        logger.info("子表  ----end");
                    } catch (DataAccessException e) {
                        e.printStackTrace();
                        //子表执行错误，删除主表的当前数据
                        String sql = "DELETE FROM LANTOP_FOURCHECKED WHERE ID = '" + mastId + "' ";
                        jdbcAvicit.getJdbcTemplate().execute(sql);
                    }
                }

            } catch (DataAccessException e) {
                e.printStackTrace();
            }


        }else{//没有四性检测结果

        }

        return null;
    }


    @Override
	public void removeLantopSubmitRelData(String ids, String formId) {
		// 1.解析删除ids
		String[] arrList = ids.split(";");

		String sql = "SELECT * FROM LANTOP_SUBMIT LS WHERE LS.ID = '" + formId + "\'";

		// 定义表名
		String tableName = "";

		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
		if (CommonFunction.listNotNull(list)) {
			String tableId = list.get(0).get("ARCHIVE_TABLE_ID").toString();

			String sqlTable = "SELECT * FROM CBB_TABLES WHERE ID = '" + tableId + "\'";
			List<Map<String, Object>> listTable = this.jdbcAvicit.getJdbcTemplate().queryForList(sqlTable);
			if (CommonFunction.listNotNull(listTable)) {
				tableName = listTable.get(0).get("TABLE_NAME").toString();
			}
		}

		for (String item : arrList) {

			String updateSql = "UPDATE " + tableName + " SET ARCHIVE_FLOW_STATUS='1' WHERE ID = '" + item + "\'";
			this.jdbcAvicit.getJdbcTemplate().update(updateSql);

			String submitRcdSql = SqlAllClass.delLantopSubmitRCDSql(item);
			this.jdbcAvicit.getJdbcTemplate().execute(submitRcdSql);
		}
	}
    
    /**
     * 删除lantopsubmit 关联数据
     */
    @Override
	public void removeLantopSubmitRelData(String ids, String formId, String isAn) {
		// 1.解析删除ids
		String[] arrList = ids.split(";");

		String sql = "SELECT * FROM LANTOP_SUBMIT LS WHERE LS.ID = '" + formId + "\'";
		// 定义表名
		String tableName = "";
		String nodeId = "";
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
		if (CommonFunction.listNotNull(list)) {
			String tableId = list.get(0).get("ARCHIVE_TABLE_ID").toString();
			nodeId = list.get(0).get("ARCHIVE_NODE_ID").toString();
			
			String sqlTable = "SELECT * FROM CBB_TABLES WHERE ID = '" + tableId + "\'";
			List<Map<String, Object>> listTable = this.jdbcAvicit.getJdbcTemplate().queryForList(sqlTable);
			if (CommonFunction.listNotNull(listTable)) {
				tableName = listTable.get(0).get("TABLE_NAME").toString();
			}
		}
		
		
        // 如果是卷内件数据，需要取值卷内件表的id
        if("wj".equals(isAn)){
        	String sqlIsAn = "SELECT T.ID,T.table_name FROM CBB_TABLES T LEFT JOIN CBB_TAB_NODE CTN ON CTN.TABLE_ID = T.ID WHERE  CTN.NODE_ID in('" + nodeId + "') and table_name like '%WJJ'";
        	List<Map<String, Object>> tableList = this.jdbcAvicit.getJdbcTemplate().queryForList(sqlIsAn);
        	  if (CommonFunction.listNotNull(tableList)) {
        		  tableName = tableList.get(0).get("TABLE_NAME").toString();
        	  }
        }
		

		for (String item : arrList) {
			String updateSql = "UPDATE " + tableName + " SET ARCHIVE_FLOW_STATUS='1' WHERE ID = '" + item + "\'";
			this.jdbcAvicit.getJdbcTemplate().update(updateSql);
			String submitRcdSql = SqlAllClass.delLantopSubmitRCDSql(item);
			this.jdbcAvicit.getJdbcTemplate().execute(submitRcdSql);
		}
	}

    @Override
    public  List<Map<String,Object>> executiveProcedure(String sql, String filterSql, ModelAndView mav, Map<String,Object> map) {
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
        
        if (CommonFunction.listNotNull(list)) {
            String nodeId = list.get(0).get("ARCHIVE_NODE_ID").toString();
            String tableId = list.get(0).get("ARCHIVE_TABLE_ID").toString();
            //查询表名
            String sqlTableName = "SELECT * FROM CBB_TABLES WHERE ID = '" + tableId + "\'";
            List<Map<String, Object>> listTemp = this.jdbcAvicit.getJdbcTemplate().queryForList(sqlTableName);

            String tableName = "";
            if (CommonFunction.listNotNull(listTemp)) {
                tableName = listTemp.get(0).get("TABLE_NAME").toString();
            }
            
            //------------------------------------根据角色构造新增列表的查询条件---------------------------------
            String sqlStr = "";
            // 判断角色
            String sysUserId = mav.getModel().get("sysUserId").toString();
            String sysUserName = mav.getModel().get("sysUserName").toString();
            String sysDeptId = mav.getModel().get("sysDeptId").toString();
            String orgIdentity = mav.getModel().get("orgIdentity").toString();
            StringBuffer sql01 = new StringBuffer();
            List<Map<String, Object>> list01 = new ArrayList<Map<String, Object>>();
            StringBuffer sql02 = new StringBuffer();
            List<Map<String, Object>> list02 = new ArrayList<Map<String, Object>>();
            sql01.append("SELECT SU.ID AS ID,SU.NAME AS NAME,SUR.ORG_IDENTITY AS ORG_IDENTITY ")
            	.append("FROM SYS_USER SU LEFT JOIN SYS_USER_ROLE SUR ON SU.ID = SUR.SYS_USER_ID ")
            	.append("WHERE SUR.SYS_ROLE_ID = (SELECT ID FROM SYS_ROLE SR WHERE SR.ORG_IDENTITY = '"+orgIdentity+"' AND SR.ROLE_CODE LIKE '%Sanxia_Manager_ROLE') AND SU.ID = '"+sysUserId+"'");
            list01 = this.jdbcAvicit.getJdbcTemplate().queryForList(sql01.toString());
            if(CollectionUtils.isEmpty(list01)){
            	// 判断是否兼职
            	sql02.append("SELECT SU.ID AS ID,SU.NAME AS NAME,SUR.ORG_IDENTITY AS ORG_IDENTITY ")
            	.append("FROM SYS_USER SU LEFT JOIN SYS_USER_ROLE SUR ON SU.ID = SUR.SYS_USER_ID ")
            	.append("WHERE SUR.SYS_ROLE_ID = (SELECT ID FROM SYS_ROLE SR WHERE SR.ORG_IDENTITY = '"+orgIdentity+"' AND SR.ROLE_CODE LIKE '%Parttime_Manager_ROLE') AND SU.ID = '"+sysUserId+"'");
            	list02 = this.jdbcAvicit.getJdbcTemplate().queryForList(sql02.toString());
            	if(!CollectionUtils.isEmpty(list02)){
            		// 兼职档案管理员用部门过滤
            		sqlStr = "  and (dept_Id = '"+sysDeptId+"'  or created_by = '"+sysUserId+"')   ";
            	}else{
            		// 一般用户用创建人和XMFZR过滤
            		if(tableName.indexOf("WJJ") > -1){
            			sqlStr = "   and (created_by = '"+sysUserId+"' or XMFZR like '"+sysUserName+"%') ";
            		}else{
            			sqlStr = "   and created_by = '"+sysUserId+"'  ";
            		}
            	}
            }
            //---------------------------------------------------------------------

            int page = Integer.valueOf(map.get("page").toString());
            int rows = Integer.valueOf(map.get("rows").toString());
            String sqlFile = "SELECT * FROM " + tableName + " WHERE 1=1  AND NODE_ID = '" + nodeId + "\' " + sqlStr + " AND " + filterSql;
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("SELECT\n" +
                    "\tT3.* \n" +
                    "FROM\n" +
                    "\t(\n" +
                    "\tSELECT\n" +
                    "\t\tT2.* \n" +
                    "\tFROM\n" +
                    "\t\t(\n" +
                    "\t\tSELECT\n" +
                    "\t\t\tT1.*,\n" +
                    "\t\t\tROWNUM ROW1 \n" +
                    "\t\tFROM\n" +
                    "\t\t\t(\n" +sqlFile+
                    "\t\t\t\n" +
                    "\t\t\t) T1 \n" +
                    "\t\t) T2 \n" +
                    "\tWHERE\n" +
                    "\t\tT2.ROW1 <  \n" +(page*rows+1)+
                    "\t) T3 \n" +
                    "WHERE\n" +
                    "\tT3.ROW1 > "+((page-1)*rows));
            List<Map<String, Object>> forList = this.jdbcAvicit.getJdbcTemplate().queryForList(sqlFile);
            return forList;
        }
        return null;
    }

    @Override
    public void saveSubmitItemDataAll(String formId, String ids, String sysId, String deptId, String orgId) {

        String sql = "SELECT * FROM LANTOP_SUBMIT LS WHERE LS.ID = '" + formId + "\'";

        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
        if (CommonFunction.listNotNull(list)) {
            String tableId = list.get(0).get("ARCHIVE_TABLE_ID").toString();

            String sqlTable = "SELECT * FROM CBB_TABLES WHERE ID = '" + tableId + "\'";

            String tableName = "";
            String tableTitle = "";
            List<Map<String, Object>> listTable = this.jdbcAvicit.getJdbcTemplate().queryForList(sqlTable);
            if (CommonFunction.listNotNull(listTable)) {
                Map<String, Object> stringObjectMap = listTable.get(0);
                tableName = stringObjectMap.get("TABLE_NAME").toString();
                tableTitle = stringObjectMap.get("TABLE_TITLE").toString();
            }


            String[] arrList = ids.split(";");
            try {
                for (String arg : arrList) {
                    LantopSubmitItem item = new LantopSubmitItem();
                    item.setArchiveRcdId(arg);
                    item.setArchiveTableId(tableId);
                    item.setArchiveTableName(tableName);
                    item.setArchiveTableTitle(tableTitle);
                    item.setLantopSubmitId(formId);
                    item.setOrgId(orgId);
                    item.setDeptId(deptId);
                    item.setSysId(sysId);
                    saveSubmitItemData(item);

                    String updateSql = "UPDATE " + tableName + " SET ARCHIVE_FLOW_STATUS='2' WHERE ID = '" + arg + "\'";
                    this.jdbcAvicit.getJdbcTemplate().update(updateSql);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    @Override
    public void getAllIdsList(String formId, ModelAndView mav) {
        String sql = "SELECT * FROM LANTOP_SUBMIT LS WHERE LS.ID = '" + formId + "\'";
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
        if (CommonFunction.listNotNull(list)) {
            String tableId = list.get(0).get("ARCHIVE_TABLE_ID").toString();
            String nodeId = list.get(0).get("ARCHIVE_NODE_ID").toString();
            
            // 如果是卷内件数据，需要取值卷内件表的id
            String isAn = mav.getModel().get("isAn").toString();
            if("wj".equals(isAn)){
            	String sqlIsAn = "SELECT T.ID,T.table_name FROM CBB_TABLES T LEFT JOIN CBB_TAB_NODE CTN ON CTN.TABLE_ID = T.ID WHERE  CTN.NODE_ID in('" + nodeId + "') and table_name like '%WJJ'";
            	List<Map<String, Object>> tableList = this.jdbcAvicit.getJdbcTemplate().queryForList(sqlIsAn);
            	  if (CommonFunction.listNotNull(tableList)) {
            		  tableId = tableList.get(0).get("ID").toString();
            	  }
            }
            
            mav.addObject("tableId", tableId);
            mav.addObject("nodeId", nodeId);
        }

    }

    /**
     * 根据roleId查询审批角色是不是专职档案管理员
     * @param roleId
     * @return
     */
    @Override
    public boolean getRole(String roleId) {
        String sql = "SELECT LS.id,LS.ROLE_NAME,LS.ROLE_CODE FROM sys_role LS WHERE LS.ID = '" + roleId + "\'";
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
        if(list.size()>0){
            String roleCode = list.get(0).get("ROLE_CODE").toString();
            roleCode = roleCode.substring(roleCode.indexOf("_")+1);
            if(roleCode.equals("Sanxia_Manager_ROLE")) {
                return false;
            }
        }
        return true;
    }

    @Override
    public List<Map<String, Object>> runSubmitSelList(String sql) {
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
        return list;
    }

    @Override
    public void getDealWithBusiness(String formId, String ids) throws SQLException {

        //1.删除submit item中存在的数据
        String[] arrgh = ids.split(";");

        //循环要删除的档案  在submitItem中找到对应数据删除 ID == ARCHIVE_RCD_ID
        for (String item : arrgh) {

            String sql = "DELETE FROM LANTOP_SUBMIT_ITEM LSI WHERE LSI.ARCHIVE_RCD_ID = '" + item + "\' " +
                    "AND LSI.LANTOP_SUBMIT_ID = '" + formId + "\'";

            this.jdbcAvicit.getJdbcTemplate().execute(sql);
        }


    }

    @Override
    public void updateSubmitATT7(String formId, String menuCode, String nodeId) {

        String code = menuCode + ":" + nodeId;

        String sql = "UPDATE LANTOP_SUBMIT SET ATTRIBUTE_07='" + code + "\' WHERE ID = '" + formId + "\' ";

        this.jdbcAvicit.getJdbcTemplate().update(sql);
    }

    @Override
    public void updateFjtmByIds(String ids, String tableId) {
        String tableName = "";
        // 获取表名
        StringBuffer tabSql = new StringBuffer();
        tabSql.append("SELECT TABLE_NAME FROM CBB_TABLES WHERE ID = '" + tableId + "'");
        List<Map<String, Object>> tabList = this.jdbcAvicit.getJdbcTemplate().queryForList(tabSql.toString());
        if (tabList.size() > 0) {
            for (Map<String, Object> tabMap : tabList) {
                tableName = tabList.get(0).get("TABLE_NAME") == null ? "" : tabList.get(0).get("TABLE_NAME").toString();
            }
        }
        // SanXiaFiles create by zhaoxiaolong 更新对应的附件题名
        String[] idsAry = ids.split(";");
        for (String idValue : idsAry) {
            StringBuffer sbSql = new StringBuffer();
            sbSql.append("SELECT\n" +
                    "\tS.ATTACH_NAME \n" +
                    "FROM\n" +
                    "\tSYS_ATTACHMENT S\n" +
                    "\tLEFT JOIN CBB_DOC_RELATION C ON C.ATTACHMENT_ID = S.ID \n" +
                    "WHERE\n" +
                    "\tC.RECORD_ID = '" + idValue + "' AND\n" +
                    "\t IF_DELETE = 'N' \n" +
                    "ORDER BY\n" +
                    "\tC.ATTRIBUTE_11 ASC");
            List<Map<String, Object>> mapList = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
            StringBuffer attachName = new StringBuffer();
            if (mapList.size() > 0) {
                for (Map<String, Object> map1 : mapList) {
                    String attachNameVal = map1.get("ATTACH_NAME") == null ? "" : map1.get("ATTACH_NAME").toString(); // 得到的附件名称
                    attachNameVal = attachNameVal.substring(0, attachNameVal.lastIndexOf(".")); // 去除文件名称后缀
                    attachName.append(attachNameVal + ";");
                }
            } else {
                attachName = new StringBuffer();
            }
            // 更新对应数据的附件题名字段
            StringBuffer upSql = new StringBuffer();
            upSql.append("UPDATE " + tableName + " SET FJTM='" + attachName + "' WHERE ID='" + idValue + "'");
            this.jdbcAvicit.getJdbcTemplate().update(upSql.toString());
        }
    }

    @Override
    public List<Map<String, Object>> getCbbMyUndoApply(String formId) {

        String sql = "SELECT * FROM CBB_MY_UNDO_APPLY WHERE FORM_ID = '"+ formId +"\'";
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);

        return list;
    }

    /**
     * 字段对应设置 获取对应字段
     *
     * @param param
     * @return
     */
    public Map<String, Object> toFieldMapSetItem(Map<String, Object> param) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        if (param != null && param.size() > 0) {
            String nodeType = "1";//节点类型  1:文件级表    2:案卷级表
            String tableId = "";
            String nodeId = param.get("nodeId").toString();
            String deptId = param.get("deptId") == null ? "" : param.get("deptId").toString();
            String orgId = param.get("orgId") == null ? "" : param.get("orgId").toString();
            String id = param.get("id").toString();
            String TableName = getSubmitByIds(nodeId);
            List<Map<String, Object>> mapList = jdbcAvicit.getJdbcTemplate().queryForList("SELECT * FROM "+ TableName +" WHERE ID='" + id + "'");
            Object tm = JSON.parse(JSON.toJSONString(mapList.get(0)));
            tableId = mapList.get(0).get("TABLE_ID") == null ? "" : mapList.get(0).get("TABLE_ID").toString();
            nodeId = mapList.get(0).get("NODE_ID") == null ? "" : mapList.get(0).get("NODE_ID").toString();
            if (tm != null && !"".equals(tm)) {
                String string = tm.toString();
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(string);
                if (string.contains("~")) {
                    nodeType = "2";
                    String[] split = string.split("~");
                    resultMap.put("OffCollistAN", parseJson1(split[0]));
                    resultMap.put("OffCollist", parseJson1(split[1]));
                } else {
                    resultMap.put("OffCollist", parseJson1(string));
                }
            }
            resultMap.put("nodeType", nodeType);
            try {
                List<Map<String, Object>> mapList1 = jdbcAvicit.getJdbcTemplate().queryForList("SELECT CT.* FROM CBB_TABLES CT LEFT JOIN CBB_TAB_NODE CTN ON CT.ID=CTN.TABLE_ID WHERE CTN.NODE_ID='" + nodeId + "' AND CTN.ORG_ID='" + orgId + "'");
                if ("1".equals(nodeType)) {
                    List<Map<String, Object>> list = this.commTableManagerIntfsService.getCbbTabColumnsByIsAllByIntfs(orgId, deptId, "LANTOP", tableId, "N");
                    resultMap.put("TableName", mapList1.get(0).get("TABLE_TITLE"));
                    resultMap.put("TagColList", list);
                } else {
                    String anTableId = "";
                    String wjTableId = "";
                    if (mapList1 != null && mapList1.size() > 0) {
                        for (Map<String, Object> map : mapList1) {
                            if (map.get("TABLE_NAME").toString().contains("AJJ")) {
                                anTableId = map.get("ID").toString();
                                resultMap.put("anTableName", map.get("TABLE_TITLE"));
                            } else {
                                wjTableId = map.get("ID").toString();
                                resultMap.put("wjTableName", map.get("TABLE_TITLE"));
                            }
                        }
                    }
                    List<Map<String, Object>> anList = this.commTableManagerIntfsService.getCbbTabColumnsByIsAllByIntfs(orgId, deptId, "LANTOP", anTableId, "N");
                    List<Map<String, Object>> wjList = this.commTableManagerIntfsService.getCbbTabColumnsByIsAllByIntfs(orgId, deptId, "LANTOP", wjTableId, "N");
                    resultMap.put("TagColListAN", anList);
                    resultMap.put("TagColList", wjList);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            resultMap.put("msg", "参数异常!");
        }
        return resultMap;
    }




    private List<Map<String, Object>> parseJson1(String json) {
        List<Map<String, Object>> OffCollist = new ArrayList<>();
        Map map = JSON.parseObject(json);
        int i=0;
        for (Object colName : map.keySet()) {
            Map<String, Object> colMap = new HashMap<>();
            if (colName != null && !"".equals(colName)) {
                colMap.put("COL_NAME", colName);
                String o = map.get(colName) == null ? "" : map.get(colName).toString();
                if (!"".equals(o) && o.split(",").length == 2) {
                    colMap.put("COL_LABEL", o.split(",")[0]);
                    colMap.put("COL_TYPE", o.split(",")[1]);
                }
            }
            colMap.put("ID",i);
            OffCollist.add(colMap);
            i++;
        }
        return OffCollist;
    }

     /**
      * @Description 获取文书类最大序号
      * @return
      * @Author zcl
      * @Date 2020/1/10 15:19
      **/
    @Override
    public List<Map<String, Object>> getMAXORDERById(String sysId, String orgId, String deptId, String userId, String type) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT MAX(TO_NUMBER(ATTRIBUTE_04)) AS TNUM FROM LANTOP_SUBMIT   WHERE ");
        sql.append("  SUBMIT_USER_ID='" + userId + "' AND");
        sql.append("  ORG_ID='" + orgId + "'AND");
        sql.append("  SYS_ID='" + sysId + "'AND");
        sql.append("  DEPT_ID='" + deptId + "'AND");
        sql.append("  ATTRIBUTE_03='" + type + "'");
        return this.jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
    }
    /**
     * @Description 判断数据来源
     * @Author zcl
     * @Date 2020/1/10 15:19
     **/
    @Override
    public Map<String, String> judgeDataSource(String idsAll, String tableId) {
        Map<String, String> result = new HashMap<String, String>();
        String ids[] = idsAll.split(";");
        String sql = "SELECT CT.TABLE_NAME FROM CBB_TABLES CT WHERE CT.ID = '" + tableId + "'";
        Map<String, Object> queryForMap = this.jdbcAvicit.getJdbcTemplate().queryForMap(sql);
        String tableName = queryForMap.get("TABLE_NAME").toString();
        here:
        for (int i = 0; i < ids.length; i++) {
            String id = ids[i];
            String sqlSer = "SELECT TM FROM "+tableName+" WHERE ID = '" + id + "'";
            Map<String, Object> queryTmForMap = this.jdbcAvicit.getJdbcTemplate().queryForMap(sqlSer);
            String TM = queryTmForMap.get("TM").toString();
            if(TM.endsWith("招标采购档案")){
                result.put("type", "1");
                result.put("TM", TM);
                break here;
            }else if(TM.endsWith("合同签订档案")){
                result.put("type", "2");
                result.put("TM", TM);
                break here;
            }else{
                result.put("type", "0");
            }
        }
        return result;
    }

    /**
     * @Description 删除流程，文书类审批标题序号置为-1
     * @return
     * @Author zcl
     * @Date 2020/1/13 19:07
     **/
    @Override
    public void updateSerialNumber(String formId) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT ATTRIBUTE_04 FROM LANTOP_SUBMIT  WHERE ");
        sql.append("  ID='" + formId + "'");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql.toString());
        Object obj = list.get(0).get("ATTRIBUTE_04");
        if(null != obj){
            Integer num = Integer.parseInt(obj.toString());
            if(num.intValue() >= 1){
                StringBuffer updateSql = new StringBuffer();
                updateSql.append("UPDATE LANTOP_SUBMIT set ATTRIBUTE_04 = '-1'");
                updateSql.append(" WHERE ID='" + formId + "'");
                this.jdbcAvicit.getJdbcTemplate().update(updateSql.toString());
            }
        }
    }
    
    /**
     * 根据表ID，获取整理中最大保管号
     * @param roleId
     * @return 
     * @throws
     */
    @Override
    public String getBghBytableName(String tableId,String nodeId) {
    	String maxbgh = "";
    	//根据表ID获取表名
    	StringBuffer sbSql = new StringBuffer();
    	sbSql.append("SELECT T.TABLE_NAME FROM CBB_TABLES T WHERE T.ID = '" + tableId + "'"); 
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        String tableName = "";
        for (int i = 0; i < list.size(); i++) {
        	Map<String, Object> m = list.get(0);
        	tableName = String.valueOf(m.get("TABLE_NAME"));
		}
        if(!"".equals(tableName) && null != tableName && !"null".equals(tableName)){
        	//计算最大保管号
        	StringBuffer sbSql1 = new StringBuffer();
        	sbSql1.append("SELECT DECODE(MAX(ZLH),\n");
        	sbSql1.append("              NULL,\n");
        	sbSql1.append("              0,\n");
        	sbSql1.append("              MAX(ZLH)) + 1 ZLH\n");
        	sbSql1.append("  FROM " + tableName + " T\n");
        	sbSql1.append(" WHERE T.ARCHIVE_STATUS <> '-1'\n");
        	sbSql1.append("   AND T.ZLZT = '2'"); 
        	sbSql1.append("   AND T.NODE_ID = '" + nodeId + "'"); 
            List<Map<String, Object>> list1 = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql1.toString());
            for (int i = 0; i < list1.size(); i++) {
            	Map<String, Object> p = list1.get(0);
            	maxbgh = String.valueOf(p.get("ZLH"));
			}
        }
        return maxbgh;
    }

    /**
     * 根据节点Id获取节点类型
     * @param nodeId
     * @return
     * @throws Exception
     */
    @Override
    public String getNodeTypeByNodeId(String nodeId) throws Exception{
        String sql = "SELECT Y.ID,Y.ARCHIVE_CLASS_NODE_NAME,Y.ARCHIVE_TYPE,Y.ARCHIVE_CLASS_NODE_TYPE " +
                "FROM LANTOP_ARCHIVE_CLASS Y WHERE ID ='"+nodeId+"'";
        //ARCHIVE_TYPE 档案类型。-1：物理表；0：模板文件夹；1：标识文件；2：档案；3：专题库；4：多媒体；5：项目归档计划；6：管务；7：其他；10：公共字段
        List<Map<String, Object>> list1 = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
        Map<String, Object> stringObjectMap = list1.get(0);
        String archive_type = stringObjectMap.get("ARCHIVE_TYPE")==null?"1":stringObjectMap.get("ARCHIVE_TYPE").toString();
        return archive_type;
    }

    /**
     * 根据表单ID删除归档流程数据
     * @param formId
     */
    @Override
    public void delLantopSubmitAnditem(String formId) throws Exception{
        String delSql = "DELETE FROM LANTOP_SUBMIT WHERE ID='"+formId+"'";
        String delSqlZ = "DELETE FROM LANTOP_SUBMIT_ITEM WHERE LANTOP_SUBMIT_ID='"+formId+"'";
        this.jdbcAvicit.getJdbcTemplate().update(delSql);
        this.jdbcAvicit.getJdbcTemplate().update(delSqlZ);
    }

    /**
     * 根据多个条目ID 修改归档单位信息
     * @param ids
     * @param tableName
     * @param deptId
     * @param orgId
     * @param deptName
     * @return
     */
    @Override
    public Map<String, Object> updateGddwInfoByIds(String ids, String tableId, String deptId, String orgId, String deptName) {
        Map<String, Object> result= new HashMap<>();
        result.put("status", OpResult.success.ordinal());
        result.put("des","");
        String[] idList = ids.split(",");
        String sql = "select TABLE_NAME FROM cbb_tables where ID = '"+tableId+"'";
        List<Map<String, Object>> maps = jdbcAvicit.getJdbcTemplate().queryForList(sql);
        String tableName = maps.get(0).get("TABLE_NAME").toString();
        for (String id : idList) {
            StringBuffer updateSql = new StringBuffer("");
            updateSql.append("UPDATE "+tableName +" T \n");
            updateSql.append(" SET T.ARCHIVE_DEPT = '"+deptName+"',ORG_ID = '" + orgId + "',DEPT_ID = '" + deptId + "'\n");
            updateSql.append(" WHERE T.ID = '"+id+"' ");
            try {
                jdbcAvicit.getJdbcTemplate().update(updateSql.toString());
            } catch (DataAccessException e) {
                result.put("status", OpResult.failure.ordinal());
                result.put("des","修改数据异常!");
                return result;
            }
        }
        return result;
    }
}
